简体   繁体   中英

Environment variables in build and run time with webpack 5

in my code I have process.env that I need to define in the run time, not the build time. Is there any way to achieve it? I would like to build the bundle for a specific reason and use the envs to determine the environment, but the app is ran on a different machine than it's being built, so I need to pass some envs in the build time and run time.

What would be the webpack way to differentiate the envs - these that are available in the build time and these available in the run time?

"build": "webpack --mode=production",
"build:qa": "ENV=qa webpack --mode=production",
"build:prod": "ENV=prod webpack --mode=production",

Webpack's DefinePlugin allows you to create global variables which can be configured at compile time. This enables you to change the behavior of your code in different environments ( eg production and dev ).

This is how you can use DefinePlugin:

new webpack.DefinePlugin(
 Object.keys(process.env)
 .filter((key) => key.startsWith(‘WEBPACK_DEMO_’))
 .reduce(
 (result, key) => ({
 …result,
 [`process.env.${key}`]: JSON.stringify(process.env[key])
 }),
 {}));
```

This goes through the keys you have in your local 'process.env' and filters them to keys that only start with the string 'WEBPACK_DEMO_'. It then reduces through these keys and builds an object from these with 'process.env' as a prefix. This way of setting environment variables at build time to use at runtime gives you the most control but also requires a larger amount of code.

For more about other approaches, you can visit here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM