Magento 2 – Load Custom JavaScript with RequireJS

adminhtmljavascriptmagento2theme

The Problem

I want to use custom JavaScript in Products/Inventory/Catalog page to modify the "Add Product" button behavior and hide some fields in product edit form (where the SKU, weight, name, qty, etc, of a product, is shown) as well.

What I've Done

For that reason, I've created an admin theme as described in this question: How to create admin theme for Magento2

The admin theme was successfully created and all static content was generated without problems. After that, I tried to load my custom js in all admin pages by doing the following:

In design/adminhtml/myvendor/mytheme/Magento_Theme/adminhtml/layout/default_head_blocks.xml

<?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>
        <script src="js/customAdmin"/>        
    </head>
</page>

In folder design/adminhtml/myvendor/mytheme/web/js/ is customAdmin.js

And in design/adminhtml/myvendor/mytheme/web/requirejs-config.js

var config = {
    "shim": {
        "customAdmin": {
            deps: ["jquery"]
        }
    },
    "paths": {
        "customAdmin": "js/customAdmin"
    }
};

Nonetheless, the js file is not loaded on any admin page.

Does anyone know what could be the problem?

Thanks.

Best Answer

See what is below

requirejs-config.js

var config = {
    map: {
        '*': {
            customAdmin: 'Namespace_Modulename/js/customAdmin'
        }
    },
    deps: ["jquery"]
};

or use in phtml:

<script>
require(['jquery', 'Namespace_Modulename/js/customAdmin'],
    function ($) {
        return ...;
    }
);
</script>



or use requirejs-config.js and phtml:

var config = {
    map: {
        '*': {
            customAdmin: 'Namespace_Modulename/js/customAdmin'
        }
    }
};


<script>
require(['jquery', 'customAdmin'],
    function ($) {
        return ...;
    }
);
</script>
Related Topic