I have a 3rd party module installed in app/code/ that has a js file injected to the product page via the frontend/layout/default_head_blocks.xml script tag:
<?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="Vendor_Module::js/filename.js" />
</head>
</page>
I need to customize that js file so I've copied the file into my theme folder (app/design/frontend/MyThemeFoler/MyThemeName/Vendor_Module/web/js/filename.js), made all the changes needed, tested it and my changes work.
But my changes are very small (just 3 lines) while the js file is very long and involves a lot of code and methods that I don't need to touch. So I wondered if there was a way to extend the file instead of overriding in order to avoid to copy the whole file but only the method that I need to change.
Is this possible?
1 Answer 1
you can try to apply your changes via mixin. https://developer.adobe.com/commerce/frontend-core/javascript/mixins/
You can either add your code to be called before/after the original code or even replace the related method completely with your own. The remaining code stays the same.
Small example: I had an issue with Magento_ReCaptchaFrontendUi/js/reCaptcha causing js errors. To avoid those errors, I added a mixin to apply my fix.
app/code/VENDOR/MODULE/view/frontend/web/requirejs-config.js
var config = {
config: {
mixins: {
'Magento_ReCaptchaFrontendUi/js/reCaptcha': {
'<VENDOR>_<MODULE>/js/recaptcha-fix': true
}
},
}
};
_/js/recaptcha-fix.js
define(function() {
'use strict';
return function(target) {
return target.extend({
initCaptcha: function () {
if (typeof this.settings === 'undefined') {
return;
}
return this._super(); // calls the original method
},
getIsInvisibleRecaptcha: function () {
if (typeof this.settings === 'undefined') {
return;
}
return this._super(); // calls the original method
}
});
}
});
Wherever the related js component is used in Magento, your mixin is automatically applied.