How to Create Custom Require JS File in Magento 2?

Hello Magento Friends,

Sometimes, you may need to create a custom RequireJS file to add custom functionality or extend existing features. In this blog, we will guide you through the process of creating a custom RequireJS file in Magento 2.

Before diving into the implementation, it’s important to understand how Magento 2 utilizes RequireJS. Magento 2 uses RequireJS to load JavaScript modules asynchronously, which helps in improving page load times by only loading the necessary scripts when required. The requirejs-config.js file is where you configure your custom JavaScript files, dependencies, and paths.

Steps to Create Custom Require JS File in Magento 2:

Step 1: Create a “di.xml” file inside the Extension etc folder.

app\code\Vendor\Extension\etc

Then add the code as follows

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\RequireJs\Config\File\Collector\Aggregated">
        <plugin name="requirejsConfigPlugin"
                type="Vendor\Extension\Plugin\RequireJs\AfterFiles"
                sortOrder="100"
        />
    </type>
</config>

Step 2: Now create the “Afterfiles.php” file inside the Extension Plugin folder.

app\code\Vendor\Extension\Plugin\RequireJs

And include the code as below

<?php

namespace Vendor\Extension\Plugin\RequireJs;

use Vendor\Extension\Helper\Data;
use Magento\Framework\Component\ComponentRegistrar;
use Magento\Framework\Component\ComponentRegistrarInterface;
use Magento\Framework\RequireJs\Config\File\Collector\Aggregated;
use Magento\Framework\View\File;
use Magento\Framework\View\File\Factory;

class Afterfiles
{
    const MODULE_NAME = 'Vendor_Extension';
    
    protected $fileFactory;
    private $componentRegistrar;

    public function __construct(
        Factory $fileFactory,
        ComponentRegistrarInterface $componentRegistrar,
    ) {
        $this->fileFactory = $fileFactory;
        $this->componentRegistrar = $componentRegistrar;
    }

    /**
     * Load mage-requirejs-config.js when meet the condition
     * @param Aggregated $subject
     * @param $result
     * @return File[]
     */
    public function afterGetFiles(
        Aggregated $subject,
        $result
    ) {
    	    /* You can add your custom conditions here to check extension enable or disable */
            $currentModulePath = $this->componentRegistrar->getPath(ComponentRegistrar::MODULE, self::MODULE_NAME);
            $fileName = $currentModulePath.'/view/frontend/mage-requirejs-config.js';
            $newFile = $this->fileFactory->create($fileName, self::MODULE_NAME, null, false);
            $result[] = $newFile;
            return $result;
    }
}

Step 3: Now create the “mage-requirejs-config.js” file inside the Extension Web folder.

app\code\Vendor\Extension\view\frontend\

Then, add the following code

Note: Here, we have overridden the login.js file. You can override the file as per your requirement.

var config = {
    map: {
        '*': {
            'Magento_Customer/js/action/login' : 'Vendor_Extension/js/action/login',
        }
    }
};

Step 4: Now override the “login.js” file inside the Extension js folder.

app\code\Vendor\Extension\view\frontend\web\js\action

Now add the following code snippet

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define([
    'jquery',
    'mage/storage',
    'Magento_Ui/js/model/messageList',
    'Magento_Customer/js/customer-data',
    'mage/translate'
], function ($, storage, globalMessageList, customerData, $t) {
    'use strict';
    /* custom require js call check */
     console.log('called Custom js');
    var callbacks = [],

        /**
         * @param {Object} loginData
         * @param {String} redirectUrl
         * @param {*} isGlobal
         * @param {Object} messageContainer
         */
        action = function (loginData, redirectUrl, isGlobal, messageContainer) {
            messageContainer = messageContainer || globalMessageList;
            let customerLoginUrl = 'customer/ajax/login';

            if (loginData.customerLoginUrl) {
                customerLoginUrl = loginData.customerLoginUrl;
                delete loginData.customerLoginUrl;
            }

            return storage.post(
                customerLoginUrl,
                JSON.stringify(loginData),
                isGlobal
            ).done(function (response) {
                if (response.errors) {
                    messageContainer.addErrorMessage(response);
                    callbacks.forEach(function (callback) {
                        callback(loginData);
                    });
                } else {
                    callbacks.forEach(function (callback) {
                        callback(loginData);
                    });
                    customerData.invalidate(['customer']);

                    if (response.redirectUrl) {
                        window.location.href = response.redirectUrl;
                    } else if (redirectUrl) {
                        window.location.href = redirectUrl;
                    } else {
                        location.reload();
                    }
                }
            }).fail(function () {
                messageContainer.addErrorMessage({
                    'message': $t('Could not authenticate. Please try again later')
                });
                callbacks.forEach(function (callback) {
                    callback(loginData);
                });
            });
        };

    /**
     * @param {Function} callback
     */
    action.registerLoginCallback = function (callback) {
        callbacks.push(callback);
    };

    return action;
});

Output:

output requirejs

Conclusion:

Creating a custom RequireJS file in Magento 2 allows you to add bespoke functionality and enhance the front-end experience of your e-commerce store. By following the steps outlined above, you can seamlessly integrate custom JavaScript modules into your Magento 2 store, ensuring that your code is organized, maintainable, and performs optimally.

If you have any questions or run into issues, feel free to leave a comment below, and we’ll be happy to help!

Happy Coding!

Previous Article

Hyvä Theme Case Study: India Cakes - Online Cake Delivery, India

Next Article

Essential Tools for Shopify App Developers

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨