TransWikia.com

Magento 2 - How to add custom JS file path into CMS Block

Magento Asked on December 8, 2020

How to get JS file in the blocks,

How to declare like:

<script type="text/javascript"> 
    src="{{skin url=''}}js/my_custom.js">
</script>

My JS path:

app/design/frontend/Codazon/fastest/grocery_gourmet/web/js/my_custom.js

OR Recommended way to declare JS.

One Answer

In Magento 2, you need to add and declare your js file via RequireJS

So:

app/design/frontend/Codazon/fastest/requirejs-config.js

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

app/design/frontend/Codazon/fastest/web/js/my_custom.js

define(['jquery'], function($){
   "use strict";
       return function myscript()
       {
           alert("Yes, it woooorks!");
       }
});

app/design/frontend/Codazon/fastest/Magento_Theme/templates/{yourfile}.phtml

    <script>
        require(['jquery', 'myscript'], function($, myscript) {
            myscript();
        });
    </script>

PS you also need to:

  • clean the cache => php bin/magento c:c

  • clean var/view_preprocessed content => rm -rf var/view_preprocessed/*

  • clean pub/static content => rm -rf pub/static/*

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

Good luck!

Answered by PЯINCƏ on December 8, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP