Loading...
Desktop - 57.jpg

How To Override node_module Files In PWA-Studio?

Introduction

Node_Module files are a necessary part of any Node.js project, but they can also be a source of headaches. How do you override them when you need to change your code?

Node_Module files are like any other Node.js file, but they contain code automatically compiled and minified when you build your project. It should add optimizations and decreases the time it takes to deploy your application. Although there are a few factors to consider when making modifications to Node_Module files that do not affect the rest of your codebase. You can override them in these cases by using the required function. Override Node_Module files by using the required function.

Step-1

If you want to override a specific file in node_module in PWA Studio, then you need to follow some steps mentioned below.

  • Create a plugin folder in our src folder.
Step-1

Step-2

  • Create the moduleOverridePlugin.js file inside the plugin folder.
Step-2

Step-3

  • Create a mapping.js file inside the plugin folder, like in the previous step.
Step-3

Step-4

  • Put the code snippet in moduleOverridePlugin.js, you can copy from here.
const path = require('path');
const glob = require('glob');
module.exports = class NormalModuleOverridePlugin {
    constructor(moduleOverrideMap) {
        this.name = 'NormalModuleOverridePlugin';
        this.moduleOverrideMap = moduleOverrideMap;
    }
    requireResolveIfCan(id, options = undefined) {
        try {
            return require.resolve(id, options);
        } catch (e) {
            return undefined;
        }
    }
    resolveModulePath(context, request) {
        const filePathWithoutExtension = path.resolve(context, request);
        const files = glob.sync(`${filePathWithoutExtension}@(|.*)`);
        if (files.length === 0) {
            throw new Error(`There is no file '${filePathWithoutExtension}'`);
        }
        if (files.length > 1) {
            throw new Error(`There is more than one file '${filePathWithoutExtension}'`);
        }
        return require.resolve(files[0]);
    }
    resolveModuleOverrideMap(context, map) {
        return Object.keys(map).reduce(
            (result, x) => ({
                ...result,
                [require.resolve(x)]:
                this.requireResolveIfCan(map[x]) || this.resolveModulePath(context, map[x])
            }),
            {}
        );
    }
    apply(compiler) {
        if (Object.keys(this.moduleOverrideMap).length === 0) {
            return;
        }
        const moduleMap = this.resolveModuleOverrideMap(compiler.context, this.moduleOverrideMap);
        compiler.hooks.normalModuleFactory.tap(this.name, nmf => {
            nmf.hooks.beforeResolve.tap(this.name, resolve => {
                if (!resolve) {
                    return;
                }
                const moduleToReplace = this.requireResolveIfCan(resolve.request, {
                    paths: [resolve.context]
                });
                if (moduleToReplace && moduleMap[moduleToReplace]) {
                    resolve.request = moduleMap[moduleToReplace];
                }
                return resolve;
            });
        });
    }
};

Step-5

After completing the preceding steps, you must map the node_module files and save them in your project folder.

  • Create lib/componenets folder in the src.
  • Suppose you want to override the Header file from the node_modules.
  • Create Header folder in src/lib/components.
  • In Header, create header.js file and write your own code.

Step 6:

In mapping.js add the following code:

module.exports = componentOverrideMapping = {
    [`@magento/venia-ui/lib/components/Header/header.js`]: 'src/lib/components/Header/header.js, 
};

Step: 7

In your pwa folder, locate the local-intercept.js file and add the below code:

const moduleOverridePlugin = require('./src/plugin/moduleOverridePlugin');
const componentOverrideMapping = require('./src/plugin/mapping');
function localIntercept(targets) {
    targets.of('@magento/pwa-buildpack').webpackCompiler.tap(compiler => {
        new moduleOverridePlugin(componentOverrideMapping).apply(compiler);
    })
}
module.exports = localIntercept;
  • Fire yarn install
  • Fire yarn build

Essence

Overriding node_module files in Project PWA provides developers with the ability to customize and extend the functionality of existing modules. By selectively modifying these files, developers can tailor the behaviour and appearance of their PWA Studio to meet specific requirements, creating a more personalized and unique user experience.

 

Contact us:+91 8128405131

Email send us at hello@elightwalk.com

Jayram Prajapati
Full Stack Developer

Jayram Prajapati brings expertise and innovation to every project he takes on. His collaborative communication style, coupled with a receptiveness to new ideas, consistently leads to successful project outcomes.

Most Visited Blog

Blog
Venia Step-Up: Elevate Your Storefront Experience

Venia Step-Up can take your storefront to new heights. Enhance your Magento PWA experience with features, customization possibilities, and a unified user experience. Investigate the next step in retail excellence.

Read More
Blog
How to show Toast message at Top In Magento PWA?

Enhance user experience in PWA store by following our advice on presenting top toast messages. Learn how to integrate and customize toast messages on your Magento PWA storefront to improve user interaction and communication.

Read More
Blog
Why Should You Think About Node.Js Development? A Definitive Guide

Discover the compelling reasons behind choosing Node.js, unravel its applications, and gain valuable insights for your projects. Unlock the potential of NodeJs Development with our comprehensive guide.

Read More