Magento 2 – Custom JS File Not Working

javascriptmagento2magento2.2.2

Currently I am working in magento2 theme part. And I have a main.js file which I have added via default_head_blocks.xml . But its having jquery conflict. I removed jquery conflict using noConflict. When I do this my testimonial section which consists of owl carousel doesnt work. Please tell me how to add my 'main.js' file.

or
Can someone tell me how to include the functions in 'main.js' on header to display the banner and drop-down menu?

Best Answer

Try this:

Update your require-config.js file this content:

var config = {
    paths: {
            'bootstrap_min': '{{module Package name}}_{{module name}}/js/vendor/bootstrap.min.js',
            'custom_main': '{{module Package name}}_{{module name}}/js/main.js'
    },
shim: {
    'bootstrap_min': {
        deps: ['jquery']
    },
    'custom_main': {
        deps: ['jquery']    
    }
};

Then You need to call that files in your PHTML:

require(['jquery', 'custom_main']);

And main.js content should be like this:

define([
    'jquery',
    '{{module Package name}}_{{module name}}/js/vendor/bootstrap.min'
], function ($,bootstrapMin) {

    "Your main.js file code put here."

});

If your file in theme then file should be in app/design/frontend/{{theme package name}}/{{theme name}}/{{Module package name}}_{{module name}}/web/js/main.js AND If your file in module then file should be in app/code/{{Module package name}}/{{module name}}/view/frontend/web/js/main.js.