在我的项目中,我想导入特定的模块,只有在编译时才知道它们的实际路径。
假设我有组件/ A.js ,组件/ B.js 和组件/ C.js 以及我的< strong> App.js 我想要包含一些只在webpack编译时知道的子集(例如来自json)
我尝试了什么 - 1
//App.js
compileData = await getCompileDataSomehow()
import("./components/" + compileData.component + ".js")
.then( /* Do stuff with component */);
这项工作很好,但是webpack会为每个components/*.js
文件创建一个块。还会有额外的网络往返。我觉得这有点矫枉过正,因为我知道webpack运行时我想要的组件。所以我试图提供组件数组而没有运气,因为require([...])
也被认为是动态的。
我最终得到了什么
//App.js
import("./components/ALL.js") //this file doesn't actually exists
//webpack.config.js
const fs = require('fs')
const componentsToInclude = ["A", "B"] //this will be read from a json
fs.writeFileSync('./src/components/ALL.js',
`
export default [
${componentsToInclude.map(comp => `require("./${comp}.js")` )}
].map(c => c.default);
`)
module.exports = { // config //}
这个有效!但正如您所看到的,这不是一个优雅的解决方案,并且很容易发生错误。那么有谁知道处理这种情况的正确方法呢?