1

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

please give me details for this process.

Rakesh Jesadiya
42.5k19 gold badges135 silver badges186 bronze badges
asked Oct 26, 2016 at 13:32

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>
answered Oct 26, 2016 at 13:37
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. Commented 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>
}});
answered Oct 26, 2016 at 13:37

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.