How To

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:

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!

Click to rate this post!
[Total: 0 Average: 0]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

Magento 2: How to Add View Button in Admin Grid to Open a View Page in Slide Window

Hello Magento Friends, In Magento 2, customizations to the admin panel can significantly enhance the…

12 hours ago

Magento 2: How to Observe the Multi-shipping Order Creation Event

Hello Magento Friends, Magento 2 provides a robust event-driven architecture that allows developers to observe…

3 days ago

Hyvä Theme FAQs

Hyvä is gradually gaining popularity in this current market, and even 3.5% of Magento websites…

4 days ago

What is Curbside Pickup?

In today’s fast-paced society, where convenience and safety are paramount, curbside pickup has emerged as…

4 days ago

What is a Planogram?

Have you ever observed how complementary and similar items are often displayed together in brick-and-mortar…

4 days ago

Hyvä Checkout – A Real Game Changer

You may be familiar with Hyvä, the frontend theme for Magento 2, which has been…

4 days ago