本节内容派生于以下链接指向的内容 ,并遵守 CC BY 4.0 许可证的规定。
以下内容如果没有特殊声明,可以认为都是基于原内容的修改和删减后的结果。
DefinePlugin 在编译时将代码中的变量替换为其他值或表达式。这对于允许开发构建和生产构建之间的不同行为非常有用。如果你在开发构建中执行日志记录,但在生产构建中则不执行,你可能会使用一个全局常量来决定是否进行日志记录。这正是 DefinePlugin 的用武之地,为开发和生产构建设置一成不变的规则。
new rspack.DefinePlugin({
// 定义...
});type CodeValue = RecursiveArrayOrRecord<CodeValuePrimitive>;
type CodeValuePrimitive =
| null
| undefined
| RegExp
| Function
| string
| number
| boolean
| bigint;
type RecursiveArrayOrRecord<T> =
| { [index: string]: RecursiveArrayOrRecord<T> }
| Array<RecursiveArrayOrRecord<T>>
| T;
type DefinePluginOptions = Record<string, CodeValue>;传入 DefinePlugin 的每个键都是一个标识符或多个标识符用 . 连接。
typeof,它只在 typeof 调用中被定义。这些值将被内联到代码中,允许在压缩阶段删除掉那些冗余的条件判断。
new rspack.DefinePlugin({
PRODUCTION: JSON.stringify(true),
VERSION: JSON.stringify('5fa3b9'),
BROWSER_SUPPORTS_HTML5: true,
TWO: '1+1',
'typeof window': JSON.stringify('object'),
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
});console.log('Running App version ' + VERSION);
if (!BROWSER_SUPPORTS_HTML5) require('html5shiv');
在为 process 定义值时,推荐使用 'process.env.NODE_ENV': JSON.stringify('production') 而不是 process: { env: { NODE_ENV: JSON.stringify('production') } }。使用后者会重写 process 对象,这可能会破坏对某些模块的兼容性,这些模块期望 process 对象上的其他值被定义。
请注意,由于插件直接执行文本替换,因此提供给它的值必须包含字符串内部的实际引号。通常,这是通过使用交替引号,如 '"production"',或使用 JSON.stringify('production') 来完成。
if (!PRODUCTION) {
console.log('Debug info');
}
if (PRODUCTION) {
console.log('Production log');
}通过 Rspack,但不进行压缩后的结果为:
if (!true) {
console.log('Debug info');
}
if (true) {
console.log('Production log');
}在压缩后的结果为:
console.log('Production log');使用特性标志在生产/开发构建中启用/禁用功能。
new rspack.DefinePlugin({
NICE_FEATURE: JSON.stringify(true),
EXPERIMENTAL_FEATURE: JSON.stringify(false),
});在生产/开发构建中使用不同的服务 URL:
new rspack.DefinePlugin({
SERVICE_URL: JSON.stringify('https://dev.example.com'),
});