You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Webpack使其构建时不转换process.env环境变量?

How to keep Webpack from replacing process.env variables so they can be set at runtime

It looks like your current Webpack build is replacing process.env.DBID with undefined because it’s trying to inject environment variables during the build phase (and since you don’t set DBID then, it defaults to undefined). To make DBID configurable when running the built app instead, you need to tell Webpack to leave process.env.DBID as-is so Node.js can resolve it at runtime.

Here’s how to fix this:

1. Set Webpack's target to node (critical for server-side code)

Since you’re building a Node.js server (server.js), you need to configure Webpack to target the Node.js environment. This tells Webpack not to replace Node.js-specific globals like process—instead, it leaves them intact so Node.js can handle them at runtime.

Add this to your Webpack config file:

module.exports = {
  // ... your other config options
  target: 'node', // This is the key line
};

2. Avoid injecting DBID via DefinePlugin/EnvironmentPlugin

If you’re using Webpack’s DefinePlugin or EnvironmentPlugin to inject other environment variables (like NODE_ENV), make sure you don’t include DBID in those plugins. These plugins replace variables during build time, which is exactly what you want to avoid for DBID.

Example with DefinePlugin:

const webpack = require('webpack');

module.exports = {
  target: 'node',
  plugins: [
    new webpack.DefinePlugin({
      // Only inject variables you need at build time
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
      // DO NOT add 'process.env.DBID' here
    }),
  ],
};

Example with EnvironmentPlugin:

If you use EnvironmentPlugin, list only the variables you want injected during build—exclude DBID:

new webpack.EnvironmentPlugin(['PORT', 'NODE_ENV']),

3. Rebuild and test

Run your original build command again:

cross-env PORT=4000 NODE_ENV=production WEBPACK_CONFIG=browser_prod,server_prod webpack --colors

Now your built server.js will keep the original line:

const baas = process.env.DBID; console.log('baas', baas);

When you run the app with your desired DBID value:

DBID=someotherid node dist/server.js

The baas variable will correctly resolve to someotherid at runtime.


内容的提问来源于stack exchange,提问作者tsdexter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:40:12