Magento 2 – How RequireJS Module Name Converts to URL

javascriptmagento2PHPrequirejs

In Magento 2, you can use RequireJS to include a javascript module with code that looks something like this.

#File: app/code/Package/Name/view/frontend/requirejs-config.js
var config = {
    map: {
        '*': {
            modulename: 'Package_Name/js/path/to/file'
        }
    }
}

While the requirejs-config.js file is a bit of Magento 2 magic, this appears to be standard RequireJS. You're basically mapping the short name modulename to the javascript module named Package_Name/js/path/to/file.

What's not clear is where or how Magento 2 converts the javascript module name above

Package_Name/js/path/to/file

Into the HTTP(S) url

//magento.example.com/static/frontend/Magento/luma/en_US/Package_Name/js/path/to/file.js

In a stock RequireJS system, RequireJS would try to load the following URL

//magento.example.com/Package_Name/js/path/to/file.js

So clearly Magento's doing something to ensure the above URL is converted into a Magento frontend URL. What's not clear is

  1. Where this happens (PHP layer? Javascript layer?)
  2. What the rule for that conversion are. The RequireJS module doesn't look like a standard Magento file identifier (Package_Name::js/path/to/file)

So, how/where does Magento 2/RequireJS convert the module into a path.

Best Answer

RequireJS has a feature that allows you to set a custom baseUrl.

Magento generates baseUrl for RequireJS in the body of the page, where JS resources are requested. So, it's basically one more part of RequireJS config generated by Magento. This baseUrl is calculated on server side and is based on current theme, locale and base URL for static view files for the store. Then native RequireJS functionality calculates full path as follows

baseUrl + file + '.js'