Create RequireJS aliases with map and paths

We have a certain naming format that we're following, but it's getting pretty long. When we need to use this code in many places throughout our codebase, it's best to have a more concise alias. We can achieve this with RequireJS by modifying the requirejs-config file.

Defining a Map Property

Open up the requirejs-config file and define a map property to the JavaScript object. Under the map, we'll define an asterix, which means that our RequireJS modules can use the alias. Assign this value to another object, and define a property as an alias. In our example, we used the fadeInElement variable name as the alias. The value of this alias will be the long string format for fadeInElement.

After saving the requirejs-config file, we can replace the original call with the alias fadeInElement in the block-promo-effects.phtml file. This will give us nice consistency with the naming of the dependency and the variable name. Save the file and refresh the page to ensure it still works.

Using Paths for External Files

In the requirejs-config file, we can also set paths. While "map" is great, it only works with local AMD modules. To alias any files, including external files, we can use paths. This follows a similar format to map.

Add another property called "paths" and define a new property called "vue". Assign the location of the Vue.js framework file to this property. This way, we can bring the Vue.js framework into our Magento module.

We'll use Vue.js version 2 for this demonstration, as it works well with RequireJS. Visit the Vue.js website, navigate to the Get Started section, and find the URL for the Vue.js file. Copy the contents of the file and paste it into a new file named vue.js within the web/js folder.

Now, we can use the "vue" alias in our RequireJS dependencies, and it'll automatically map to the js/vue file within the web/js folder. This will work even though Vue.js isn't an AMD module, because paths allow us to import pretty much any JavaScript file.

As an alternative, we can grab the URL for the Vue.js file and replace the contents of our local directive with the production directive. Remember to remove the .js extension because RequireJS will automatically request that. Now, when we use the "vue" alias, it will automatically look at the CDN and pull out the external JavaScript file.

Complete and Continue  
Extra lesson content locked
Enroll to access all lessons, source code & comments.
Enroll now to Unlock