Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

please give me details for this process.

share|improve this question
up vote 3 down vote accepted

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>
share|improve this answer
    
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 at 12:41

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>
}});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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