本文大约二千字,看完本文大概须要二十分钟,动手尝试须要一小时css
前段时间作项目,技术栈是vue+webpack,主要就是官网首页加后台管理系统 根据当时状况,分析出三种方案html
上一张多页面的结构图 前端
npm install vue-cli -g
vue init webpack multiple-vue-amazing
复制代码
npm install glob --save-dev
复制代码
修改src文件夹下面的目录结构vue
/* 这里是添加的部分 ---------------------------- 开始 */
// glob是webpack安装时依赖的一个第三方模块,还模块容许你使用 *等符号, 例如lib/*.js就是获取lib文件夹下的全部js后缀名的文件
var glob = require('glob')
// 页面模板
var HtmlWebpackPlugin = require('html-webpack-plugin')
// 取得相应的页面路径,由于以前的配置,因此是src文件夹下的pages文件夹
var PAGE_PATH = path.resolve(__dirname, '../src/pages')
// 用于作相应的merge处理
var merge = require('webpack-merge')
//多入口配置
// 经过glob模块读取pages文件夹下的全部对应文件夹下的js后缀文件,若是该文件存在
// 那么就做为入口处理
exports.entries = function () {
var entryFiles = glob.sync(PAGE_PATH + '/*/*.js')
var map = {}
entryFiles.forEach((filePath) => {
var filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.'))
map[filename] = filePath
})
return map
}
//多页面输出配置
// 与上面的多页面入口配置相同,读取pages文件夹下的对应的html后缀文件,而后放入数组中
exports.htmlPlugin = function () {
let entryHtml = glob.sync(PAGE_PATH + '/*/*.html')
let arr = []
entryHtml.forEach((filePath) => {
let filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.'))
let conf = {
// 模板来源
template: filePath,
// 文件名称
filename: filename + '.html',
// 页面模板须要加对应的js脚本,若是不加这行则每一个页面都会引入全部的js脚本
chunks: ['manifest', 'vendor', filename],
inject: true
}
if (process.env.NODE_ENV === 'production') {
conf = merge(conf, {
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
},
chunksSortMode: 'dependency'
})
}
arr.push(new HtmlWebpackPlugin(conf))
})
return arr
}
/* 这里是添加的部分 ---------------------------- 结束 */
复制代码
webpack.base.conf.js 文件node
/* 修改部分 ---------------- 开始 */
entry: utils.entries(),
/* 修改部分 ---------------- 结束 */
复制代码
webpack.dev.conf.js 文件jquery
/* 注释这个区域的文件 ------------- 开始 */
// new HtmlWebpackPlugin({
// filename: 'index.html',
// template: 'index.html',
// inject: true
// }),
/* 注释这个区域的文件 ------------- 结束 */
new FriendlyErrorsPlugin()
/* 添加 .concat(utils.htmlPlugin()) ------------------ */
].concat(utils.htmlPlugin())
复制代码
webpack.prod.conf.js 文件webpack
/* 注释这个区域的内容 ---------------------- 开始 */
// new HtmlWebpackPlugin({
// filename: config.build.index,
// template: 'index.html',
// inject: true,
// minify: {
// removeComments: true,
// collapseWhitespace: true,
// removeAttributeQuotes: true
// // more options:
// // https://github.com/kangax/html-minifier#options-quick-reference
// },
// // necessary to consistently work with multiple chunks via CommonsChunkPlugin
// chunksSortMode: 'dependency'
// }),
/* 注释这个区域的内容 ---------------------- 结束 */
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
/* 该位置添加 .concat(utils.htmlPlugin()) ------------------- */
].concat(utils.htmlPlugin())
复制代码
npm install element-ui bootstrap-vue --save
复制代码
分别在不一样的页面引入不一样的ui index.jsnginx
import BootstrapVue from 'bootstrap-vue'
Vue.use(BootstrapVue)
复制代码
admin.jsgit
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
复制代码
上面多页面的配置是参考网上的,并且网上的思路大都很类似,核心就是改多个entry,配置完成了以后,开发的时候也是发现不了问题的,而后大概就开发了一个月,开发完以后对官网进行性能分析时发现,webpack打包的vendor.js网络加载时间特别长,致使首屏的白屏时间很是长,最终经过-webpack-bundle-analyzer分析获得告终论github
npm run build --report
复制代码
既然是vendor过大引发加载速度慢,那就分离这个vendor就行了。我是这样想的,把各个页面中都使用到的第三方代码提取至vendor.js中,而后各个页面中用到的第三方代码再打包成各自的vendor-x.js,例如现有页面index.html、admin.html,则最终会打包出vendor.js、vendor-index.js、vendor-admin.js。
webpack.prod.conf.js 文件
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor-admin',
chunks: ['vendor'],
minChunks: function (module, count) {
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(path.join(__dirname, '../node_modules')) === 0 &&
module.resource.indexOf('element-ui') != -1
)
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor-index',
chunks: ['vendor'],
minChunks: function (module, count) {
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(path.join(__dirname, '../node_modules')) === 0 &&
module.resource.indexOf('bootstrap-vue') != -1
)
}
}),
复制代码
再次分析,一切都很ok,vendor.js被分离成了vendor.js、vendor-index、vendor-admin.js
这个问题其实就是HtmlWebpackPlugin的问题 把原来的 chunksSortMode: 'dependency'改为自定义函数的配置,以下
util.js文件
chunksSortMode: function (chunk1, chunk2) {
var order1 = chunks.indexOf(chunk1.names[0])
var order2 = chunks.indexOf(chunk2.names[0])
return order1 - order2
},
复制代码
其实多页面之间抽离公共的文件的场景,中大型项目会用的比较多,最初是看到下面评论说须要抽离common-api的时候会多打包出来common-api.css,而且有同窗私信我遇到一些关于commonChunk的问题,我作一个更新,并提供思路
需求:项目中一些公共的js甚至是css,可复用到每个page里边,例如admin.js引用common-api.js,index.js也引用了common-api.js。如今抽离多个页面之间公共的模块common-api
新建一个common/index.js 直接引用一个本地文件js(我这里用jquery来代替公共js)
在admin.js index.js里引用
import $ from '../../common'
console.log($('body'))
复制代码
打包明显能发现jquery被打包了两次,资源浪费了。
坑就是必须指定chunks 否则会报错webpack ERROR in CommonsChunkPlugin: While running in normal mode it's not allowed to use a non-entry chunk
一开始有位同窗问我这个错误怎么解决,一开始我也不知道,后来查阅了一些资料,发现只要指定了chunks就能够解决这个错误,贴一段github的issues,感兴趣的能够深刻了解
从新指定util.js 里面的htmlPlugin的顺序
let chunks = filename === 'admin' ?
['manifest', 'vendor', 'vendor-admin', 'common-api', filename] :
['manifest', 'vendor', 'vendor-index', 'common-api', filename]
复制代码
最后看看结果,抽离出来了common-api,jq只被加载了一次, 而且并无多打包出来common-api.css,html里面script的顺序也是对的
大功告成了,虽然配置看起来很简单,不过我当时开发的时候,思考了好久,因此假如你CommonsChunkPlugin和HtmlWebpackPlugin不熟悉或者只会用别人第三方的配置表,估计会踩大坑,好比说,CommonsChunkPlugin不指定chunks,默认是什么?minChunks大多数人只会写一个数值,然而自定义一个函数的写法其实才是最强大的,根据我我的的经验chunks结合minChunks自定义函数的写法,能解决几乎全部CommonsChunkPlugin灵异的事件。
虽然本篇文章是基于webpack3来说的,可是webpack4多页面配置和优化打包的思想其实也是同样的,放心大胆的使用吧,有坑就解决它。
本文源码喜欢点个赞