webpack 打包
1. 提取项目公共资源。
- 插件:HtmlWebpackExternalsPlugin。
使用:
//1. 配置文件
module.export = {
// 省略
plugins: [
new HtmlWebpackExternalsPlugin({
externals: [
{
modules: 'react',
entry: 'cdn地址/本地地址',
global: 'React'
}
]
})
]
}
// 2. 模板文件
;<script type="text/javascript" src="cdn地址/本地地址">
{' '}
</script>
1. 打包体积分析
- webpack 内置 stats 对象
- speed-measure-webpack-plugin
- 代码
const speedMeasureWebpackPlugin = require('speed-measure-webpack-plugin') const smwp = new speedMeasureWebpackPlugin() const webpackConfig = smwp.wrap({ plugins: [] })
- webpack-bundle-analyzer
2. 打包速度
-
多线程打包
-
happypack
```javascript const HappyPack = require('happypack') module.export = { // 省略 rules: [ { test: /.js$/, //loaders: 'babel-loader' use: ['happypack/loader'] } ], plugins: [ new HappyPack({ loaders: ['babel-loader'] }) ] } ```
-
Thread-loader
```javascript const ThreadLoader = require('thread-loader') module.export = { // 省略 rules: [ { test: /.js$/, //loaders: 'babel-loader' use: [ { loader: 'thread-loader', options: { workers: 3 } }, 'babel-loader' ] } ] } ```
-
-
多线程、多实例 并行压缩
-
uglifyjs-wepack-plgin 开启 parallel
const UglifyjsWebpackPlugin = require('uglifyjs-wepack-plgin') module.export = { // 省略 plugins: [ new UglifyjsWebpackPlugin({ uglifyOptions:{ warnings: false, parse: {}, compress: {}, mangle: true, output: null, toplevel:false, nameCache: null, ie8:false, keep_fnames: false }, parallel:true }) ] }
-
terser-webpack-plugin 开启 parallel
const TerserWebpackPlugin = require('terser-webpack-plugin') module.export = { // 省略 optimization: { minimizer: [ new TerserWebpackPlugin({ parallel: 4 }) ] } }
-
-
分包
- DLLPlugin 分包 DllReferencePlugin 对于 manifest.json 的引用。将我们的基础库合并生成一个.dll 文件。
// package.json { "scripts": { 'dll': 'webpack --config webpack.dll.js' // script 标签添加对应的执行语句,生成对应的manifest.json } } // webpack.dll.js 类似webpack的配置文件 const path = require('path') const webpack = require('webpack') module.export = { resolve: { extensions: ['.js', '.jsx', '.json', '.less', '.sass'], modules: [__dirname, 'node_modules'] }, entry: { library: ['react', 'react-dom', 'redux', 'react-redux'] }, output: { filename: '[name]_[chunkhash].dll.js', path: resolve(__dirname, './build/library'), name: '[name]' }, plugins: [ new webpack.DLLPlugin({ name: '[name]', path: './build/library/[name].json' }) ] } // webpack.config.js module.export = { // 省略 plugins: [ new webpack.DllReferencePlugin({ manifest: require('./build/library/library.json') }) ] }
-
二次打包缓存
- babel-loader
module.export = { //省略 rules: [ { test: /.js$/, loaders: 'babel-loader?cache=true' } ] }
- terser-webpack-plugin
module.export = { //省略 optimization: { minimiser: [ new TerserWebpackPlugin({ parallel: true, cache: true }) ] } }
- hard-source-webpack-plugin
module.export = { //省略 plugins: [new HardSourceWebpackPlugin()] }
-
缩小构建目标
module.export = {
//省略
resolve: {
alias: {
xxxx: 'xxx'
},
modules: [path.resolve(__dirname, 'node_modules')],
extensions: ['.js', '.jsx', '.json', '.less', '.sass'],
mainFields: ['main']
}
}