You often need to change the JavaScript code logic located in the .js file. The easiest way is to override the js file is by using a theme. You can learn how to override view files in the article about Overriding Magento 2 Storeftont Files. This is a quick but not an elegant way.
To change one or more js-file methods, use the mixins available in RequireJS.
To extend this file:
app/code/VendorName/ModuleName/view/%area%/web/js/folder1/folder2/somefile.js
with the following code:
define(
[
'jquery',
'underscore',
'ko',
'uiComponent',
'uiRegistry',
],
function (
$,
_,
ko,
Component,
registry,
) {
'use strict';
return Component.extend({
// ...
method1: function() { /* some code */ },
method2: function() { /* some code */ }
// ...
}); }
);
%area% - the area where the file is extended, for example: frontend, adminhtml, base.
To override the method1, you need to create basic module, and add the following 2 files to it:
1. requirejs-config.js
This is the RequireJS configuration file where the mixer is added. Create it in the module folder, with the following path:
view/%area%/requirejs-config.js
and add this code:
var config = {
config: {
mixins: {
'VendorName_ModuleName/js/folder1/folder2/somefile' : {'My_Module/js/folder1/folder2/somefile-mixin':true}
}
},
}
2. The mixin somefile-mixin.js itself.
Save it in your module folder with this path:
view/%area%/web/js/folder1/folder2/somefile-mixin.js
and add the following code:
define(
[
'jquery',
'underscore',
'ko',
'uiComponent',
'uiRegistry',
],
function (
$,
_,
ko,
Component,
registry,
) {
'use strict';
var mixin = {
method1: function() { /* my code */ },
};
return function (target) {
return target.extend(mixin);
};
}
);
Once you save the changes don't forget to deploy static content by running this command:
php bin/magento setup:static-content:deploy