WebPack Vendor Bundling @ Modern Web and App Programming
WEBPACK @ MODERN WEB AND APP PROGRAMMING 之後,開始進入到 vendor bundling 的概念
以下參考這部影片
當有二個以上 entry point 時,可以如下寫法
module.exports = {
context: path.resolve(__dirname, './src'),
entry: {
main: './main.js',
module: './module-1.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].bundle.js'
}
};
這時就會發生一個問題,例如
main.js
module-1.js
都有 import lodash
產生 bundling 時,自然也就會產出二個 bundle js,裡面都有 lodash
這時就需要 vendor bundling 了
前往 webpack.config.js 編輯如下
// in webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
context: path.resolve(__dirname, './src'),
entry: {
main: './main.js',
module: './module-1.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].bundle.js'
},
plugins : [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: 'vendor.bundle.js',
minChunks: 2
// 重複 2 次以上就包到 vendor
}),
]
};
記得 html 檔也要 include 產出的 vendor.bundle.js (先 include vendor)
<script src="vendor.bundle.js"></script>
<script src="main.bundle.js"></script>
<script src="module.bundle.js"></script>
如果要手動指定包裝的 package,也可以如下把 lodash 另外包出來
module.exports = {
context: path.resolve(__dirname, './src'),
entry: {
main: './main.js',
vendor: ['lodash', ...]
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].bundle.js'
},
plugins : [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: 'vendor.bundle.js',
minChunks: Infinity
}),
]
};
Comments
Post a Comment