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".
Answer
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;
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM