(转载文章)
公司的平台功能越堆越多,打包也越来越费劲,一次十几分钟,运维很不爽,so捣鼓了一下预编译,试了一下大概缩短了七八分钟,目前感觉还行,现在把它记下来,给需要的童鞋当做参考,也给自己记录一下。
项目目录
-
build
- webpack.dll.conf.js(我们自己新建的预编译配置)
- webpack.base.config.js
- webpack.prod.conf.js
- ....
- static
- package.json
新建文件webpack.dll.conf.js
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',}),*/],};
webpack.base.conf.js文件配置,在开发或打包时能引用或避开预编译下的内容
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const manifest = require('../static/dll/lib-manifest.json')
添加插件配置
plugins: [//自定义dllnew webpack.DllReferencePlugin({context: __dirname+'/static/dll',manifest: manifest,dll:`${manifest.name}.js`,}),//全局库绑定new webpack.ProvidePlugin({$: 'jquery',jQuery: 'jquery',"window.jQuery": 'jquery',"window.$": 'jquery',}),
],
在webpack.prod.conf.js文件配置打包
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里面引用这个dlldll:`/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 CommonsChunkPluginchunksSortMode: 'dependency'}),
根目录下的 index.html,body的结束标签前加上
<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...