【Webpack】开发环境优化

1、HMR 热模块替换

当一个模块改变时,只重新打包这一个模块,提升了构建速度

  devServer: {
    static: './dist',
    hot:true//开启 HMR
  },
  1. 样式文件:可以使用 HMR 功能,因为 style-loader 内部实现了
  2. js 文件:默认不能使用 HMR 功能
  3. html 文件:默认不能使用 HMR 功能,同时不能热更新(解决:在 entry 入口处添加 html 文件),但是一般不用做
entry: ['./src/index.js','./src/index.html'],

2、source-map

一种提供源代码到构建后代吗映射技术,(如果构建后代码出错了,通过映射可以追踪到源代码错误),在 webpack.config.js 中添加:

devtool:'source-map'

开发环境下:

  1. 速度快:(eval > inline > cheap)
  2. 调试更友好:(source-map > cheap-module-source-map > cheap-cource-map)

在大多数情况下,最佳选择是 eval-cheap-module-source-map

3、oneOf

可以将各种 loader 放入一个数组中,数组为 oneof

  module: {
    rules: [
        {
            oneOf:[
                {
                    test: /\.css$/i,
                    use: ['style-loader', 'css-loader'],
                },
                {
                    test: /\.(png|svg|jpg|jpeg|gif)$/i,
                    type: 'asset/resource',
                },
                {
                    test:/\.js$/,
                    exclude:/node_modules/,
                    loader:'eslint-loader',
                    options:{
                        fix:true
                    }
                },
            ]
        },
    ],
  },

这样只会执行一次 loader 操作,但是不能将操作同样文件的 loader 一起放入 oneOf 中,将多余的放到外面来

4、缓存

  1. 通过babel 缓存(让第二次打包构建速度更快)
module: {
    rules: [
             {
        test:/\.js$/,
        exclude:/node_modules/,
        loader:'babel-loader',
        options:{
            preset:[
                [
                    '@babel/preset-env',
                    {
                        useBuiltIns:'usage',
                        corejs:{
                            version:3
                        },
                        targets:{
                            chrome:'60',
                            firefox:'60'
                        }
                    }
                ]
            ],
            //开启 babel 缓存
            cacheDirectory:true
        }
      }
    ],
  },
  1. 通过文件名改变来缓存(让代码上线运行缓存更好使用,存在浏览器上)
  output: {
    filename: 'main.[contenthash:10].js',
    path: path.resolve(__dirname, 'dist'),
    clean: true,
  },

由于每次输出文件都会产生新的 hash 值,将其添加到输出文件名中可以起到缓存的作用
image

5、tree shaking 去除无用代码

前提:1、必须使用 ES6 模块化,2、开启 production 环境

6、懒加载

image

posted @ 2022-01-28 21:26  RikkaXl  阅读(94)  评论(0)    收藏  举报