RequireJS is a JavaScript file and module loader. It enables asynchronous JavaScript loading(JavaScript to load in the background).
In Magento 2, we have requirejs-config.js
file with a single root object config
which contains the configuration options. These configuration settings are optional and are used only when required. Here is an example ofrequirejs-config.js
with all the options :
var config = {
map: {...},
paths: {...},
deps: [...],
shim: {...},
config: {
mixins: {...},
text: {...}
}
}
We can declare the requirejs-config.js file specific to the scope(frontend or adminhtml).
map
The map
configuration is used to connect or map any real AMD modules to the specified alias. Also, it is used to override a JS module with a custom JS module.
var config = {
map: {
'*': {
exitpopup: 'Webiins_ExitPopup/js/exitpopup'
}
}
};
paths
The paths
configuration is used for aliasing, not just any real AMD module that calls define(), but also any URLs and third-party libraries.
var config = {
...
paths: {
exitpopup: 'Webiins_ExitPopup/js/exitpopup'
'exitpopup2': 'https://webiins.com/jsfile'
}
};
deps
The deps
configuration is used to add a dependency. It can be used directly under var config = {}
or under shim configuration. When we add modules under an independent deps
configuration will load the specified modules in all pages.
var config = {
deps: [
'Magento_Theme/js/theme'
]
};
shim
Since we cannot modify third-party libraries, shim
configuration is used to build a dependency on them.
var config = {
shim: {
'3rd-party-library': ['customJSFile']
}
};
mixins
The mixins
configuration is used to overwrite component methods of an AMD module that returns either a UI component, a jQuery widget, or a JS object.
var config = {
config: {
mixins: {
'Magento_ConfigurableProduct/js/configurable': {
'Webiins_Payment/js/configurable-mixin': true
},
'Magento_Tax/js/view/checkout/summary/grand-total': {
'Webiins_Payment/js/view/checkout/summary/grand-total-mixin': true
}
}
}
};
text
The text
configuration is used to set the security request headers.
config: {
text: {
'headers': {
'X-Requested-With': 'XMLHttpRequest'
}
}
}