前端項目構建過程當中,爲了提升構建效率,用上cache,每每會將第三方庫和本身的業務邏輯代碼分開打包,在Webpack
裏有兩個插件能夠完成這項任務,CommonsChunk
和DLL & DllReference
html
能夠將相同的模塊提取出來單獨打包,進而減少 rebuild 時的性能消耗,可是每次構建時都須要執行一次,顯然很浪費時間前端
相比於前者,經過前置這些依賴包的構建,來提升真正的 build 和 rebuild 的構建效率。也就是說只要第三方庫沒有變化,以後的每次build都只須要去打包本身的業務代碼。這個思路應該來源於Windows的動態連接庫 (DLL)
react
如何使用DLL & DllReference
在這裏再也不敖述,網上資料仍是比較多的,能夠參考 https://segmentfault.com/a/11...webpack
使用DLL & DllReference
後,第三方庫的確前置構建了,可是如何讓打包出來的bundle文件在index.html中引用呢?若是output.fileName寫死名字,在index.html中也寫死,就沒有了強緩存,若是ouput.fileName=[name].[hash].js,就得找到一個往html裏添加js的辦法git
When working with Webpack you might want to generate your bundles with a generated hash in them (for cache busting).github
This plug-in outputs a json file with the paths of the generated assets so you can find them from somewhere else.web
有了這個插件,看起來就行得通了,在打包第三庫時使用assets-webpack-plugin
將bundle的文件名輸出,保存成json,在打包業務代碼時配合html-webpack-plugin
插件,將bundle添加到index.html中json
webpack.dll.config.jsredux
const webpack = require('webpack'); const AssetsPlugin = require('assets-webpack-plugin'); module.exports = { entry: { bundle: [ 'history', 'react', 'react-router', 'react-dom', 'react-redux', 'react-router', 'react-router-redux', 'redux', 'redux-thunk' ] }, output: { path: '/', filename: '[name].[hash].js', library: '[name]_library' }, plugins: [ new webpack.DllPlugin({ path: '/', name: '[name]_library' }), new AssetsPlugin({ filename: 'bundle-config.json', path: '/' }), ] };
webpack.config.jssegmentfault
const webpack = require('webpack'); const bundleConfig = require("/bundle-config.json"); module.exports = { entry: { app: ['./app.tsx'] }, output: { path: '/', publicPath: '', filename: '[name]-[hash].js', chunkFilename: '[name]-[chunkhash].js' }, plugins: [ new HtmlwebpackPlugin({ filename: 'index.html', chunks: ['app'], template: 'app.html', bundleName: bundleConfig.bundle.js, minify: __DEV__ ? false : { collapseWhitespace: true, collapseInlineTagWhitespace: true, removeRedundantAttributes: true, removeEmptyAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true, removeComments: true } }), new webpack.DllReferencePlugin({ context: '.', manifest: require('/bundle-manifest.json') }) ] };
app.html裏須要用到這樣的模版 <%= htmlWebpackPlugin.options.bundleName %>
到這裏,整個構建過程就比較舒服了,不重複打第三方庫的包,也用上了強緩存
更詳細的代碼能夠參考我搭的這個腳手架 https://github.com/bccsafe/Re...