Search code examples
javascriptreactjstypescriptwebpackcreate-react-app

How to make dynamic import/require depend of variable with code cleanup?


I have react app created by "react-create-app" with latest react 16.12 and Webpack

I need to make import with dependence on variable, like it:

    if (process.env.SOMEVAR === "a1") Routes = require("./xxx").default;
    if (process.env.SOMEVAR === "a2") Routes = require("./yyy").default;
    if (process.env.SOMEVAR === "a3") Routes = require("./zzz").default;

Run command: set "SOMEVAR=a1" && npm run build

This code will make main.chunk.js with this 3 modules xxx/yyy/zzz inside, without dependency of SOMEVAR

I've accidentally discovered that when I use NODE_ENV variable name - it works like I need! Example:

    if (process.env.NODE_ENV === "production") Routes = require("./xxx").default;
    if (process.env.NODE_ENV === "development") Routes = require("./yyy").default;
    if (process.env.NODE_ENV === "test") Routes = require("./zzz").default;

Run command: set "NODE_ENV=production" && npm run build

This code will make main.chunk.js with only xxx module inside!

Question: How to make any other variables with same effect instead of NODE_ENV (I need to have inside of build only modules which uses after my if)? How it works? I cant find any info about this effect in "WebPack docs".


Solution

  • From the provided example i think this is not the best approach.

    You can define a dynamic pluggin in that exposes a custom global variable to the build. Adding to your webpack plugins config something like :

    new webpack.DefinePlugin({
        EnabledRoutes: {
            testing: true,
            production: true,
            development: true
        }
    })
    

    And this way you can use process environment or reading a build config like this:

    new webpack.DefinePlugin({
        EnabledRoutes: {
            testing: process.env.ROUTES_TESTING,
            production: Config.routes.production,
            development: true
        }
    })
    

    And in the client router directly you can check to add the additional routes:

    if(EnabledRoutes.testing)
    {
        APPEND routes.
    }
    

    or

    if (EnabledRoutes.testing) Routes = require("./xxx").default;