1

How can I add custom js file and compile using requirejs file in magento 2 ?

please give me details for this process.

2 Answers 2

3

Keep your js file inside app/design/frontend/Vendor/themename/Vendor_Modulename/web/js/custom.js

You can add js using xml file with default.xml file,

  <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <head>
            <link src="Vendor_Modulename::js/custom.js"/>
        </head>
        <body>      
        </body>
    </page>

Run command to get js at compile time, php bin/magento setup:static-content:deploy

You can call js inside phtml file by calling,

<script>
  require(["jquery"],function($){ 
     // your js code
  })
</script>

Second way,

create requirejs-config.js file, inside app/design/frontend/Vendor/themename/Vendor_Modulename/requirejs-config.js file

add js file inside, app/design/frontend/Vendor/themename/Vendor_Modulename/web/js/customfile.js file

 var config = {
        map: {
            '*': {
                customjs: 'Vendor_Modulename/js/customfile'
            }
        }
    };

call inside template file,,

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

            $('selector').customjs({
            });

    });
</script>
1
  • Just a note, it's advisable to use require.js (the second method here) instead of adding JS files via the XML. It's consistent with how Magento does it and it helps manage dependencies.
    – Ben Crook
    Oct 31, 2016 at 12:41
2

requiredjs with file name (../view/frontend/requirejs-config.js)

var config = {
"map": {
    "*": {
        "<js_tag_name>": "<vendor>_<module_name>/js/<js_name>"
    }
}

};

Add your js to ../view/frontend/web/js/.js

define([
"jquery",], function($){
return function (config, element) {
    <your_js_code>
}});

Your Answer

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

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