helloxiaoliang 2019-06-27
(转载文章)
公司的平台功能越堆越多,打包也越来越费劲,一次十几分钟,运维很不爽,so捣鼓了一下预编译,试了一下大概缩短了七八分钟,目前感觉还行,现在把它记下来,给需要的童鞋当做参考,也给自己记录一下。
项目目录
build
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var path = require('path');
var package = require('../package.json')
var outputPath = '../static/dll'
module.exports = {
output: {
path: path.join(__dirname, outputPath),
filename: 'dll.[name]_[hash:6].js',
library: '[name]_[hash:6]', // 当前Dll的所有内容都会存放在这个参数指定变量名的一个全局变量下,注意与DllPlugin的name参数保持一致
},
entry: {
//直接引用package里面的
lib: Object.keys(package.dependencies),
//也可以手动配置
lib:[
'jquery',
'vue',
'vue-router',
'swiper'
]
},
plugins: [
new webpack.DllPlugin({
path: path.join(__dirname, outputPath, '[name]-manifest.json'), // 本Dll文件中各模块的索引,供DllReferencePlugin读取使用
name: '[name]_[hash:6]', // 当前Dll的所有内容都会存放在这个参数指定变量名的一个全局变量下,注意与参数output.library保持一致
context: __dirname, // 指定一个路径作为上下文环境,需要与DllReferencePlugin的context参数保持一致,建议统一设置为项目根目录
}),
new ExtractTextPlugin('[name].css'),
/*全局库绑定不在此处配置
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery',
}),*/
],
};const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const manifest = require('../static/dll/lib-manifest.json')添加插件配置
plugins: [
//自定义dll
new webpack.DllReferencePlugin({
context: __dirname+'/static/dll',
manifest: manifest,
dll:`${manifest.name}.js`,
}),
//全局库绑定
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
"window.jQuery": 'jquery',
"window.$": 'jquery',
}),
],var manifest = require('../static/dll/lib-manifest.json')在HtmlWebpackPlugin配置里添加dll
的引用,以便在index.html里加上我们的预编译包
new HtmlWebpackPlugin({
filename: process.env.NODE_ENV === 'testing'
? 'index.html'
: config.build.index,
template: 'index.html',
//在index.html里面引用这个dll
dll:`/static/dll/dll.${manifest.name}.js`,
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'
}),<script src="<%= htmlWebpackPlugin.options.dll %>" ></script>
最后一步在package.json里边添加上预编译命令,srcipt里边加上一行:
//预编译命令 "dll": "webpack --progress --colors --config build/webpack.dll.conf.js",
项目根目录下运行npm run dll,就会在static目录下发现dll这个文件夹,里面就是预编译的包和预编译的引用json。
项目地址: https://github.com/JhonMr/pre...
原创文章,转载请注明出处 https://www.jianshu.com/p/156...