动态需要使用的WebPack的DefinePlugin多个文件?

问题描述 投票:1回答:2

我有我想要导入的文件名称的数组。文件名在构建时计算。如果我有一个文件名,我可以这样做:

new webpack.DefinePlugin({
  component_file: '"path/Component"',
})

然后在来源:

require(component_file);

这包括path/Component在构建,符合市场预期。

但是,如果我尝试以下方法,这是行不通的。

new webpack.DefinePlugin({
  component_files: ['"path/Component"', '"path/Component2"'],
})

然后在来源:

// component_files is converted object by Webpack.
Object.keys(component_files).forEach(file => require(file));

这将导致一个错误Cannot find module '0'。这是有道理的,因为的WebPack少了点静态分析,它不能与变量作为参数处理requires。是否有可能做我想要做什么?

javascript webpack
2个回答
0
投票

而不是使用DefinePlugin定义,然后你的应用程序中所需的依赖,你可以让它们包含在编译的时候把它们作为你的配置中的条目:

{
  entry: [
    ...component_files,
    'app.js'
  ]
}

0
投票

对于由环境变量实现动态绑定,你必须包装将被确定为“死代码”或没有条件块内require语句。 然后,在编译时间,这些死require声明将被移除,这将导致最终束排斥。

每个条件块的谓词必须作为生成时的布尔值进行评价。当谓词为2的原始值或纯布尔之间的滑动比较就会发生这种情况只。例如:

// webpack.config.json
new DefinePlugin({
  "process.env.component_a": "true",
  "process.env.component_b": "false",
  "process.env.component_c": "'true'",
})

// in application:
if (process.env.component_a) {
  const a = require('./a') // will be included
}
if (process.env.component_b) {
  const b = require('./b') // will be excluded
}

if (process.env.component_c === "true") {
  const c = require('./c') // will be included
}

重要的提示 离开undefined值不是从最终包不包括模块不够好。

/* THE WRONG WAY */

// webpack.config.json
new DefinePlugin({
  "process.env.component_a": "true",

})

// in application:
if (process.env.component_a) {
  const a = require('./a') // will be included
}
if (process.env.component_b) {
  // even though this block is unreachable, b will be included in the bundle!
  const b = require('./b') 
}
© www.soinside.com 2019 - 2024. All rights reserved.