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

5

2 Answers 2

3

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

1
  • It's working fine. Commented May 1, 2019 at 11:34
0

Try to remove add JS in layout.

You already declared dependencies with requireJS.

Than use in PHTML as :

require(['bootstrap'], function(bootstrap) {
  ... Your code
 });

It should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.