主要參考官網 Getting Started
本篇內容延續 Webpack2 入門(2)
本篇主要介紹:如何將我們原本打包成單一 bundle.js
改成打包成 main.js
以及 vendor.js
Getting started
在開發的過程中,我們引用的模組 node_modules
的變動頻率往往沒有我們的程式碼頻繁。如果我們每次都整個打包成 bundle.js
,會造成此檔案太過大包而且打包時間相對過久。因此我們可以將載入的模組另外打包成 vendor.js
,我們的程式碼打包成 main.js
。
打包 Main.js 及 Vendor.js
CommonsChunkPlugin(See more)
修改後的 webpack.config.js
如下:
webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: {
main: './app/index.js',
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist') // 打包到哪個資料夾
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor', // Specify the common bundle's name.
minChunks: function(module) {
// this assumes your vendor imports exist in the node_modules directory
return module.context && module.context.indexOf('node_modules') !== -1;
}
})
]
};
執行
$ npm run build
此時我們會看到 dist 資料夾底下會有 main.js
& vendor.js
。
修改我們的 index.html
如下:
index.html
<html>
<head>
<title>webpack 2 demo</title>
</head>
<body>
<a href="http://dist/vendor.js">http://dist/vendor.js</a>
<a href="http://dist/main.js">http://dist/main.js</a>
</body>
</html>
以上就完成了,結果與只打包成 bundle.js
相同