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


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">
            <link src="Vendor_Modulename::js/custom.js"/>

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

You can call js inside phtml file by calling,

     // your js code

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">


  • 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
    Commented Oct 31, 2016 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

"jquery",], function($){
return function (config, element) {

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.