首页 > 解决方案 > 当在同一行上使用“process.env”时,DefinePlugin 不会替换 var

问题描述

我正在使用webpack.DefinePlugin一个非常简单的配置来设置客户端与服务器变量:

new webpack.DefinePlugin({
  __CLIENT__: JSON.stringify(false),
})

当我在以下文件上运行它时,它只替换了 的两种用途之一__CLIENT__

export const CLIENT = __CLIENT__;
export const processEnv = __CLIENT__ ? null : process.env;

// === compiles to the following: ===>

export const CLIENT = false;
export const processEnv = __CLIENT__ ? null : process.env; // __CLIENT__ doesn't get replaced.

当我将第二行更改为具有process.env 以外的任何内容时,它工作正常。

export const CLIENT = __CLIENT__;
export const processEnv = __CLIENT__ ? null : 'works!';

// === compiles to the following: ===>

export const CLIENT = false;
export const processEnv = false ? null : 'works!'; // __CLIENT__ gets replaced.

我可以通过首先保存到以下其他一些变量来非常简单地解决这个问题__CLIENT__,但这让我完全不信任webpack.DefinePlugin未来的使用。

export const CLIENT = __CLIENT__;
export const processEnv = CLIENT ? null : process.env;

// === compiles to the following: ===>

export const CLIENT = false;
export const processEnv = false ? null : process.env; // Works, compiles fine.

也许更奇怪的是,它似乎webpack.DefinePlugin在乎我设定的价值。这编译正确:

new webpack.DefinePlugin({
  __CLIENT__: JSON.stringify(true), // Instead of false
})

...

// Same code as initial example:
export const CLIENT = __CLIENT__;
export const processEnv = __CLIENT__ ? null : process.env;

// === compiles to the following: ===>

export const CLIENT = true;
export const processEnv = true ? null : 0; // Works, compiles fine.

为什么要webpack.DefinePlugin关心我的重置价值是多少?难道我做错了什么?我应该更改其他配置吗?

标签: javascriptwebpack

解决方案


推荐阅读