Magento – Best Way to Add JS file in Magento 2 Theme

javascriptmagento2magento2.2

I have created a custom theme. I have to use bootstrap in my theme. So I am adding the JS file as follows :

In theme directory /Magento_Theme/requirejs-config.js file.

var config = {
 paths:{
"jquery.bootstrap":"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min"
},
shim:{
'jquery.bootstrap':{
    'deps':['jquery']
}
}
};

But it's not working.

I have tried with this in default_head_blocks.xml. JS file in theme/web/js directory

<script src="js/bootstrap.min.js"/>

But getting error Mismatched anonymous define() module

Best Answer

The best way to add JS is with requirejs.

To add a js in theme via Requirejs:

Supposing that your js file is: myfile.js

app/design/frontend/{Vendor}/{theme}/requirejs-config.js

var config = {
    map: {
        '*': {
            myscript: 'js/myfile'
        }
    }
};

app/design/frontend/{Vendor}/{theme}/web/js/myfile.js

define(['jquery'], function($){
   "use strict";
       return function myscript()
       {
           alert('hello myscript');
           //put all your myfile js code here
       }
});

app/design/frontend/{Vendor}/{theme}/Magento_Theme/templates/{yourfile}.phtml

<script type="text/javascript">
    require(['jquery', 'myscript'], function($, myscript) {
        myscript();
    });
</script>

Info: don't forget to :

  • clean the cache

  • clean var/view_preprocessed content

  • clean pub/static content

  • deploy the static content = php bin/magento setup:static-content:deploy -f