How Magento Includes the RequireJS library

RequireJS is a crucial component in Magento's core page layout, as it is responsible for loading JavaScript libraries. This article will guide you through the process of locating and understanding how RequireJS is implemented in Magento.

Locating RequireJS in Magento Theme Module

The Magento theme module, which drives most of the core page layout, can be found at vendor/magento/module-theme. Inside this module, search for the view/frontend/layout/default.xml file. This file is loaded on every single page of Magento.

In this file, you will find an element named require.js. To locate the template file assigned to this XML node, navigate to page/js in the templates folder, specifically page/js/require_js. This PHTML file is defined before the RequireJS library is loaded, as there are no includes for the RequireJS JavaScript file.

The PHTML file mainly defines a couple of base variables for RequireJS. The first variable defines the base URL for the site, while the second variable, Require, assigns the base URL value for the location where the JavaScript will be located. These variables are defined globally before the actual library is loaded, and RequireJS uses them in the main config object.

Locating the RequireJS Library

Since there is no script tag in the PHTML file, we need to continue searching for where RequireJS is included. Return to the default.xml file and look for the default_head_blocks handle. This is a separate XML document that defines all of the default head blocks for the store. Open this XML file, which can be found in the same directory as the default.xml file.

The XML file defines a head tag, which appears to be the actual head of the HTML, and inside of that, there's a reference to RequireJS. If there's no prefix to this source, it is likely loaded from the lib/web folder. This folder is located in the Magento root. Inside the lib/web folder, you will find JavaScript libraries such as Knockout, jQuery, and RequireJS.

Upon opening the require.js folder, you will find the actual RequireJS library that Magento uses for loading.

Now that we have identified and located RequireJS in Magento, you can confidently use it anywhere within the Magento framework.

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