How Can I Resolve a RequireJS Alias in Magento 2?
-
30-09-2020 - |
Question
From a Disqus comment on my website
When I look at this file: vendor/magento/module-catalog/view/base/templates/product/price/tier_prices.phtml
I see something like this
<script type="text/x-magento-init">
{
".product-info-main": {
"addToCart": {
"origin": "tier",
"addToCartButton": "#product_addtocart_form [type=submit]",
"inputQty": "#qty",
"attr": "[data-tier-price]",
"productForm": "#product_addtocart_form",
"productId": "",
"productIdInput": "input[type=hidden][name=product]",
"isSaleable": ""
}
}
}
</script>
The "addToCart" should be some javascript file according to this article, but it is not. Maybe this is another feature ?
Solution
The addToCart
key is a RequireJS module. However, it's a module that's been aliased with a RequireJS feature -- most likely map
. You'll want to get familiar with the RequireJS integration in Magento if you plan on doing anything more than tinker with the front end code.
The easiest way I've found to resolve these aliases is some unix find
combined with grep
. The mapping is configured in the requirejs-config.js
files, so you can find all these files with
find vendor/magento/ -name requirejs-config.js
If you combine that with the -exec
feature of find, you can search all these files for the string addToCart
find vendor/magento/ -name requirejs-config.js -exec grep addToCart '{}' +
If you run that command, you'll get the following output
vendor/magento//module-msrp/view/frontend/requirejs-config.js: addToCart: 'Magento_Msrp/js/msrp'
If you look in the file
/* vendor/magento//module-msrp/view/frontend/requirejs-config.js */
var config = {
map: {
'*': {
addToCart: 'Magento_Msrp/js/msrp'
}
}
};
You'll see that addToCart
is aliased to the RequireJS module Magento_Msrp/js/msrp
. Without getting into how Magento serves front end files, that Magento_Msrp/js/msrp
module will resolve to the file
vendor/magento//module-msrp/view/base/web/js/msrp.js
While technique won't deterministically zero in on your file every time, I've found it works 99% of the time.