DefinePlugin 允许在 编译时 将你代码中的变量替换为其他值或表达式。这在需要根据开发模式与生产模式进行不同的操作时,非常有用。例如,如果想在开发构建中进行日志记录,而不在生产构建中进行,就可以定义一个全局常量去判断是否记录日志。这就是 DefinePlugin 的发光之处,设置好它,就可以忘掉开发环境和生产环境的构建规则。
new webpack.DefinePlugin({
  // 定义...
});传递给 DefinePlugin 的每个键都是一个标识符或多个以 . 连接的标识符。
typeof 作为前缀,它会被定义为 typeof 调用。这些值将内联到代码中,从而允许通过代码压缩来删除冗余的条件判断。
new webpack.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');if (!PRODUCTION) {
  console.log('Debug info');
}
if (PRODUCTION) {
  console.log('Production log');
}未经 webpack 压缩过的代码:
if (!true) {
  console.log('Debug info');
}
if (true) {
  console.log('Production log');
}经过压缩后:
console.log('Production log');使用 feature flags 在生产/开发构建中可以启用/禁用项目的不同特性。
new webpack.DefinePlugin({
  NICE_FEATURE: JSON.stringify(true),
  EXPERIMENTAL_FEATURE: JSON.stringify(false),
});在生产或开发构建中使用不同的服务 URL:
new webpack.DefinePlugin({
  SERVICE_URL: JSON.stringify('https://dev.example.com'),
});runtimeValuefunction (getterFunction, [string] | true | object) => getterFunction()
It is possible to define variables with values that rely on files and will be re-evaluated when such files change in the file system. This means webpack will rebuild when such watched files change.
There're two arguments for webpack.DefinePlugin.runtimeValue function:
The first argument is a function(module, key, version) that should return the value to be assigned to the definition.
The second argument could either be an array of file paths to watch for or a true to flag the module as uncacheable. Since 5.26.0, it can also take an object argument with the following properties:
fileDependencies?: string[] A list of files the function depends on.contextDependencies?: string[] A list of directories the function depends on.missingDependencies?: string[] A list of not existing files the function depends on.buildDependencies?: string[] A list of build dependencies the function depends on.version?: string | () => string A version of the function.const fileDep = path.resolve(__dirname, 'sample.txt');
new webpack.DefinePlugin({
  BUILT_AT: webpack.DefinePlugin.runtimeValue(Date.now, {
    fileDependencies: [fileDep],
  }),
});The value of BUILT_AT would be the time at which the 'sample.txt' was last updated in the file system, e.g. 1597953013291.
Webpack 5 现已正式发布。请阅读我们的 发布公告。如还未准备升级,请阅读 webpack 4 文档。