问题
在 Webpack 中导出 bundle 时,如何排除 3rd-party 模块的 peerDependency? (不是第三方模块本身)
背景
我想在 angular-material
框架之上创建一个带有自定义组件的 UIkit。使用 Webpack,我可以将我的自定义组件和 Angular Material 捆绑在一起,形成 uikit.js
之类的东西,然后稍后移植到其他应用程序。但是,我不想将 angular
模块本身包含到此 uikit.js
中。
问题
似乎 Webpack 足够“聪明”,注意到 angular
模块是 angular-material
模块的依赖项,因此会同时导出 angular
模块和 angular-material
模块到包中。可以使用 config.externals: {'angular': 'angular'}
或 new webpack.IgnorePlugin(/angular$/)
来排除 angular
模块在应用程序中明确需要,但对于 peerDependency(即 angular-material
中需要的那个),它仍会包含它。
那么,我怎样才能从导出中排除这个依赖于第 3 方的模块呢?
示例:
// app.js
var angular = require('angular');
var material = require('angular-material');
// ... other application logic
// webpack.config.js
var webpack = require('webpack');
module.exports = {
entry: {
app: './app.js'
},
module: {
loaders: [
// some module loaders
]
},
// This only excludes the angular module require by the app, not the one require by the angular-material
externals: {'angular': 'angular'},
plugins: [
// This is the same as externals, only the one required by app.js would be excluded
new webpack.IgnorePlugin(/angular$/)
]
};
最佳答案
在 webpack(第 4 版)配置中,我将 vendor 应用程序导出到 vendor 包中,并像这样分块:
entry: {
app: './app.js',
vendor: [ 'angular', 'angular-material', '...' ],
},
optimization: {
splitChunks: {
chunks: 'all',
}
},
基本上,这表明将选择哪些 block 进行优化,all
意味着即使在异步和非异步 block 之间也可以共享 block 。此外,如何构建模块以及如何处理依赖关系可以进一步简化 block 大小。
此外,您可以提供一个函数,其返回值将指示是否包含每个 block :
module.exports = {
//...
optimization: {
splitChunks: {
chunks (chunk) {
// exclude `my-excluded-chunk`
return chunk.name !== 'my-excluded-chunk';
}
}
}
};
这是一个link to webpack解释 splitChunks 插件。
关于javascript - 如何从 Webpack 的导出中排除 vendor 模块 peerDependencies?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37221172/