由於本例單入口時打包的文件體積過大,將其分成多入口。 主要涉及到的幾個文件為: /index.html, /webpack.dll.config.js, /build/webpack.base.conf.js, /build/webpack.dev.conf.js, /build/webpack.p ...
由於本例單入口時打包的文件體積過大,將其分成多入口。
主要涉及到的幾個文件為:
/index.html,
/webpack.dll.config.js,
/build/webpack.base.conf.js,
/build/webpack.dev.conf.js,
/build/webpack.prod.conf.js
- 新建文件webpack.dll.config.js,可以放置在任意位置,只要將路徑理清即可。本例以根目錄示例:
-
const fs = require('fs')
const path = require('path') const webpack = require('webpack') let vendors = [ [ 'echarts', 'echarts-wordcloud', 'element-ui' ],[ 'vue/dist/vue.esm.js', 'vue-echarts', 'vue-js-modal', 'vue-router', 'vue-waterfall', 'vuex' ] ] module.exports = { entry: {
// 多入口,單入口情況,只需寫一個,key值自定義,value值為數組 vendor0: vendors[0], vendor1: vendors[1] }, output: { path: path.join(__dirname, "static/dll"), filename: "[name].[chunkhash].dll.js", library: "[name]_[chunkhash]" }, plugins: [ new webpack.DllPlugin({ path: path.join(__dirname, "dllManifest", "[name]-manifest.json"), name: "[name]_[chunkhash]", context: __dirname }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ] }在/build/webpack.base.conf.js中增加:
-
plugins: [
// 這是一個數組,單入口時只需填寫一個對應的webpack.DllReferencePlugin實例
// webpack.DllReferencePlugin可以幫助webpack得知哪些包是dll負責的,進而避免重覆打包 ...(function () { let max = 2 let res = [] for (let i = 0; i < max; i++) { res.push(new webpack.DllReferencePlugin({ context: path.resolve(__dirname, '../'), manifest: require(resolve(`./dllManifest/vendor${i}-manifest.json`)) })) } return res })() ]在/build/webpack.dev.conf.js,/build/webpack.prod.conf.js文件HtmlWebpackPlugin實例中添加dll屬性,方便在index.html中使用:
-
new HtmlWebpackPlugin({ filename: 'index.html', template: 'index.html', inject: true, // ---------------------------------------------------- dll: (function () { let max = 2 let res = [] for (let i = 0; i < max; i++) { const dllName = require(path.resolve(__dirname, `.././dllManifest/vendor${i}-manifest.json`)).name.split('_') res.push(`/static/dll/${dllName[0]}.${dllName[1]}.dll.js`) } return res })() // ---------------------------------------------------- })
修改/index.html模板:
<!-- 要註意文件註入的位置,以免其他js運行前,找不到相關依賴 --> <% for (let i of htmlWebpackPlugin.options.dll) { %> <script src="<%= i %>"></script> <% } %>
本次主要解決的問題是:每次代碼改動重新打包花費時間過長的問題。
解決是通過webpack提供的DllPlugin完成,包括dll打包的js文件命名加上hash,以及避免每次打包需手動修改index.html模板的問題。