Webpack 的 CommonsChunkPlugin 插件,負責將多次被使用的 JS 模塊打包在一起。
CommonsChunkPlugin 能解決的問題
在使用插件前,考慮幾個問題:
以下是官方給出的常用的場景:
前面我們實現了 多頁面分離資源引用,按需引用JS和css
但有一個問題:最后生成的3個js,都有重復代碼,我們應該把這部分公共代碼單獨提取出來。
方式一,傳入字符串參數
new webpack.optimize.CommonsChunkPlugin(‘common.js'), // 默認會把所有入口節點的公共代碼提取出來,生成一個common.js
var HtmlWebpackPlugin = require('html-webpack-plugin');var webpack = require('webpack');var extractTextPlugin = require('extract-text-webpack-plugin');module.exports = { // entry是入口文件,可以多個,代表要編譯那些js //entry:['./src/main.js','./src/login.js','./src/reg.js'], entry: { 'main':'./src/main.js', 'user':['./src/login.js','./src/reg.js'], 'index':['./src/index.js'] }, externals:{ 'jquery':'jQuery' }, module:{ loaders:[ // {test://.css$/,loader:'style-loader!css-loader'}, {test://.css$/,loader:extractTextPlugin.extract('style','css')} ], }, output:{ path: __dirname+'/build/js', // 輸出到那個目錄下(__dirname當前項目目錄) filename:'[name].js' //最終打包生產的文件名 }, plugins:[ new HtmlWebpackPlugin({ filename: __dirname+'/build/html/login-build.html', template:__dirname+'/src/tpl/login.html', inject:'body', hash:true, chunks:['main','user','common.js'] // 這個模板對應上面那個節點 }), new HtmlWebpackPlugin({ filename: __dirname+'/build/html/index-build.html', template:__dirname+'/src/tpl/index.html', inject:'body', hash:true, chunks:['index','common.js'] // 這個模板對應上面那個節點 }), // css抽取 new extractTextPlugin("[name].css"), // 提供公共代碼 new webpack.optimize.CommonsChunkPlugin('common.js'), // 默認會把所有入口節點的公共代碼提取出來,生成一個common.js ]};方式二,有選擇的提取公共代碼
// 提供公共代碼// 默認會把所有入口節點的公共代碼提取出來,生成一個common.js// 只提取main節點和index節點new webpack.optimize.CommonsChunkPlugin('common.js',['main','index']), 方式三,有選擇性的提取(對象方式傳參)
推薦
new webpack.optimize.CommonsChunkPlugin({ name:'common', // 注意不要.js后綴 chunks:['main','user','index'] }),通過CommonsChunkPlugin,我們把公共代碼專門抽取到一個common.js,這樣業務代碼只在index.js,main.js,user.js
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答