提高webpack的打包速度
尽可能在更少的文件中使用loader,比如在使用babel-loader时,通过exclude来排除掉在node_modules里面的js文件,这样可以提高打包速度。
Plugin尽可能精简并且确保可靠(尽可能少的去使用插件)
resolve参数要合理配置
使用DLLPlugin提高打包速度。核心思想时利用DLLPlugin和DLLReferencePlugin预编译资源模块,通过DLLPlugin来引进那些我们引用但是绝对不会改变的npm包来进行预编译,再通过DLLReferencePlugin将预编译的模块加载进来。
- 新建一个文件,名字叫做
webpack.dll.js
,里面内容如下:
const path = require('path'); const webpack = require('webpack'); module.exports={ mode:'production', entry:{ vendors:['vue','vue-router']//这里写的是不会修改的那些只用解析一次的模块 }, output:{ filename:"[name].dll.js",//打包生成的文件名字,这里最终生成的文件是vendors.dll.js path:path.resolve(__dirname,"./dll"),//这些文件打包之后会存在dll文件夹里 library:'[name]'//将打包出来的东西暴露给全局 }, plugins:[ new webpack.DLLPlugin({ name:'[name]',//这里和output属性的libiary保持一致 path:path.resolve(__dirname,'./dll/[name].manifest.json') }) ] }
- 在package.json的script中加上一条指令:
"script":{ "build:dll":"webpack --config webpack.dll.js" }
- 在命令行里运行
npm run build:dll
- 安装另外一个插件
npm install add-asset-html-webpack-plugin -D
- 修改webpack.common.js文件,在里面新增如下内容:
const AddAssetHtmlWebpackPlugin = require('add-asset-html-webpack-plugin'); plugins:[ //这个插件的作用是往htmlwebpackplugin插件生成的html上面新增一些静态文件,这里新增的是vendors.dll.js new AddAssetHtmlWebpackPlugin({ filepath:path.resolve(__dirname,'vendors.dll.js') }), new webpack.DLLReferencePlugin({ manifest:path.resolve(__dirname,'./dll/vendors.manifest.json') }) ]
- 使用parallel-webpack,happypack多进程打包
多页面应用打包
// 多入口 let path = require('path') let HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { mode: 'development', entry: { home: './src/index.js', other: './src/other.js' }, output: { filename: "[name].js",//这里的name就是entry里面的两个文件,可以是home,也可以是other path: path.resolve(__dirname, 'dist2') }, plugins: [ new HtmlWebpackPlugin({ template: './index.html', filename: 'home.html', //在chunks里面加入你想在这个页面中引入的js文件。 chunks: ['home']//表示home.html里面引入的是打包生成的home.js }), new HtmlWebpackPlugin({ template: './index.html', filename: 'other.html', chunks: ['other', 'home'] // other.html 里面有 other.js & home.js }), ] }
- 新建一个文件,名字叫做