在尝试优化我的源代码后,我正在努力解决看起来像 Webpack 的一般错误。
假设我在 ./src 中有以下文件:
├── main.js ├── moduleA.js └── moduleB.js
main.js imports and uses ModuleA.
moduleA.js imports and uses ModuleB
ModuleA.js and ModuleB.js both import flatten-array from node_modules
我的期望是,如果我尝试优化我的包(见下文),它将输出两个文件:
1. index.js
2. vendors~main.index.js
尝试执行 index.js
输出包会导致:
/******/ modules[moduleId].call(module.exports, module,
module.exports, __webpack_require__);
^
TypeError: Cannot read property 'call' of undefined
虽然生成了文件,但 index.js
似乎并未导入vendors~main.index.js。然而,当删除优化(和 vendor JavaScript)时它执行得很好
这是正确的假设吗?我怎样才能让它像这样工作?
虽然这是 Node 的 bundle ,但我有充分的理由想要导出 vendor 文件。
随附的 git 存储库可在此处重现:
https://github.com/supasympa/webpack-vendors-issue
文件是:
main.js
const moduleA = require('./moduleA');
moduleA.log('log from main.js');
<小时/>
moduleA.js
const moduleB = require('./moduleB');
const flatten = require('array-flatten');
module.exports.log = function(msg){
moduleB.log('logging from moduleA.js');
console.log(`ModuleA logging: ${msg}`);
console.log(`flattened: ${flatten([[1,2,3],[4,5],[6,7]])}`)
};
<小时/>
moduleB.js
const flatten = require('array-flatten');
module.exports.log = function(msg){
console.log(`ModuleB logging: ${msg}`);
console.log(`flattened: ${flatten([[1,2,3],[4,5],[6,7]])}`)
};
<小时/>
webpack.config.js
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
module: {
rules: [{
include: [path.resolve(__dirname, 'src')],
loader: 'babel-loader',
options: {
plugins: ['syntax-dynamic-import'],
presets: [['env', {
'modules': 'commonjs'
}]]
},
test: /\.js$/
}]
},
entry: './src/main',
target: 'node',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist')
},
mode: 'development',
optimization: {
splitChunks: {
cacheGroups: {
vendors: {
priority: -10,
test: /[\\/]node_modules[\\/]/,
enforce: true
},
},
// concatenateModules: false,
chunks: 'all',
minChunks: 1,
minSize: 0,
name: true
}
},
plugins: [
new CleanWebpackPlugin(['dist']),
]
};
最佳答案
事实证明,这还没有在浏览器之外的 Webpack 中实现。
https://github.com/webpack/webpack/issues/8330
关于javascript - Webpack: vendor 包未在主输出中导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53142650/