Magento2 JavaScript – How to Extend/Override JS

javascriptmagento2overridesrequirejs

As Magento2 is using RequireJS for loading scripts, and there's no more skin folder, I've stuck with a problem:

How can I replace Magento's module JS file by my modified version?

For example — the opc-checkout-method.js which belongs to Magento_Checkout extension. It's not defined in the requirejs-config.js file, as far as I can see.

My extension is loaded after Magento_Checkout, so its requirejs-config.js data is appended at the end of resulting requirejs-config file.

Or should I do it in some other way, without replacing the whole script?

Best Answer

There is no more skin folder but you can still use themes.

As a proof of concept I used you example with op-checkout-method.js and this this.

Preconditions:

  • Magento2-beta11 installed
  • Default theme active (blank).
  • No files generated in the pub/static folder (remove the pub/static/frontend folder)

Actions:

  • Copied the op-checkout-method.js file from it's module location app/code/Magento/Checkout/view/frontend/web/js/opc-checkout-method.js to the blank theme to app/design/frontend/Magento/blank/Magento_Checkout/web/js/opc-checkout-method.js
  • edited the clone file and added a console.log('something') or alert('something') in the _create function of the mage.opcCheckoutMethod widget.
  • cleared browser cache.

Result:

  • When the checkout page loads I see my alert displayed or the text logged in the console.

Related Info:

If I run from cli php dev/tools/Magento/Tools/View/deploy.php (the script that publishes the static resources) my new js file gets placed in pub/static/frontend/Magento/blank/en_US/Magento_Checkout/js/opc-checkout-method.js

[EDIT]

I found a way to do it via a module.

In [Namespace]/[Module]/view/frontend/requirejs-config.js add this:

var config = {
    map: {
        '*': {
            'Magento_Checkout/js/opc-checkout-method':'[Namespace]_[Module]/js/opc-checkout-method'
        }
    }
};

Then create the file [Namespace]/[Module]/view/frontend/web/js/opc-checkout-method.js with your content.

For testing purposes I cloned the original file and just added again a console.log in the _create function.

Also remember to regenerate the public resources for frontend.