简体   繁体   English

构建和运行时的环境变量 webpack 5

[英]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.在我的代码中,我需要在运行时而不是构建时定义 process.env。 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.我想出于特定原因构建 bundle 并使用 envs 来确定环境,但是该应用程序运行在与构建它不同的机器上,因此我需要在构建时和运行时传递一些 envs。

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?区分 envs 的 webpack 方法是什么 - 这些在构建时可用,而这些在运行时可用?

"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. Webpack 的 DefinePlugin 允许您创建可以在编译时配置的全局变量。 This enables you to change the behavior of your code in different environments ( eg production and dev ).这使您能够更改代码在不同环境(例如生产环境和开发环境)中的行为。

This is how you can use DefinePlugin:这是您可以使用 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_'.这会遍历您在本地“process.env”中的密钥,并将它们过滤为仅以字符串“WEBPACK_DEMO_”开头的密钥。 It then reduces through these keys and builds an object from these with 'process.env' as a prefix.然后它通过这些键进行缩减,并从这些键中构建一个 object,并以“process.env”作为前缀。 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有关其他方法的更多信息,您可以访问此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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