Create a custom RequireJS config file
Defining RequireJS Config
The RequireJS config in Magento is defined from an initial RequireJS object on page load, as seen in the require_js.phtml
file. However, the config doesn't have to be defined in one place. Magento looks for files named requirejs-config.js
with the config variable.
When Magento finds these files, it injects the config variable into the RequireJS config.
Searching for Instances of requirejs-config.js Files
To look for instances of requirejs-config.js
files, open up the terminal and use the grep
command to search recursively for requirejs-config.js
, specifically in the vendor/magento
folder.
Inspecting the search results will reveal references to test runners, test suites, and even swagger. However, the main focus should be on the reference to the RequireJS Config class.
Examining the RequireJS Config Class
By opening up the RequireJS Config class file, you can see what's happening within the class. As you go through the Config class, you'll find references to templates and a getConfig
function. This function is responsible for looping through all the requirejs-config.js
files and injecting them into RequireJS.
The custom config files variable retrieves the files named requirejs-config.js
recursively through the design theme folder. It then loops through these files, reads them, gets the config, and uses one of the templates to inject the config.
Partial Config Template
The partial config template takes the config it finds and injects it into RequireJS. To test this functionality, create a custom module and set up a new file at view/frontend/requirejs-config.js
. Remember, Magento looks for these requirejs-config
files within a view/frontend
folder. Write some dummy output to the console, such as "we are here", and save the file.
If you go to the front end of your site, reload, and check the console for the output, you'll see that Magento is loading your call to console.log
. However, you may also notice a JavaScript error indicating that the config is not defined. This is because Magento looks for a config variable within the RequireJS file.
To resolve this error, define a config variable and set it to an empty object. After reloading the page, the error should disappear, and no errors should be output to the console. Now that you know Magento is loading your requirejs-config.js
file, you can start writing your own custom config.