webpack性能优化

114 阅读1分钟

一、打包构建速度

babel-loader

1、babel从缓存获取,没有改变的文件从缓存中获取,不需要编译所以的文件

配置:

{
  test:/\.js$/,
    use{
        loader:"babel-loader",
        options:{
            cacheDirectory:truepresets: [
                ['@babel/preset-env', {
                    useBuiltIns: 'usage',
                    corejs: 3
                }]
            ]
        }
    }
    exclude:path.resolve(__dirname,'node_modules')
}

排除某一个目录下的不需要编译 exclude:path.resolve(__dirname,'node_modules') 或者include:srcPath指向一下编译的目录

webpack.IgnorePlugin 不要一些代码打包然后按需引入,包文件中是不会出现的(体积小)适用2中环境

new webpack.IgnorePlugin(/\./locale/,/moment/)

noParse:忽略打包文件,不做解析 包文件会出现

 module.exports = {
    noParse:[/.\xx$/]
   }

多进程打包:

1、happyPack

2、多进程压缩代码:webpack-parsellel-uglify-plugin

webpack.DLLPlugin/webpack.ReferencePlugin 预先打包(开发环境)

2、应用包的体积

1、代码体积小

2、合理分包(不重复加载)

3、内存占用更小

1、小图片采用base64编码:减少http请求

2、赖加载:把不需要马上用到的代码,通过import('./xx')

3、代码分割,抽离模块的公共代码ptimization.splitChunks

4、cdn加速:

output: {
    publicPath:'http://xx.xx.com'
}

5、production:

js代码压缩为一行,
自动开启tree shaking(剔除未引用代码)适用ES Module
module.exports = {
	mode: 'production'
        }

6、Scope Hosting(作用域提升)

ModuleConcatentionPlugin

7、babel polyfill 按需引入:

presets(插件集合)

按需引入:useBuiltIns: 'usage', 指定corejs的版本: 3

{
	test: /\.js$/,
	exclude: /node_modules/,
	use: {
		loader: "babel-loader",
		options: {
			presets: [
				['@babel/preset-env', {
					useBuiltIns: 'usage',
					corejs: 3
				}]
			]
		}
	}
}