MST

星途 面试题库

面试题:Webpack CLI 脚手架搭建项目基础之配置优化

使用 Webpack CLI 脚手架快速搭建一个前端项目基础后,发现打包后的文件体积较大。请阐述至少两种优化打包体积的配置方法,并说明在 Webpack 配置文件中的具体实现。
47.8万 热度难度
前端开发Webpack

知识考点

AI 面试

面试题答案

一键面试

1. 代码压缩

在 Webpack 中可以使用 terser-webpack-plugin 来压缩代码,减少文件体积。 在 webpack.config.js 中配置如下:

const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
  optimization: {
    minimizer: [
      new TerserPlugin({
        parallel: true, // 使用多进程并行运行以提高构建速度
        terserOptions: {
          compress: {
            drop_console: true // 移除 console.log 等日志,进一步减小体积
          }
        }
      })
    ]
  }
};

2. 按需加载与代码分割

使用 splitChunks 进行代码分割,将公共代码提取出来,避免重复打包。 在 webpack.config.js 中配置如下:

module.exports = {
  optimization: {
    splitChunks: {
      chunks: 'all',
      minSize: 30000, // 模块的最小大小,小于这个值的模块不会被拆分
      minChunks: 1, // 被多少个chunk共享,在分割之前模块必须被至少这么多模块引用
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          name:'vendors',
          priority: -10
        },
        commons: {
          name: 'commons',
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true
        }
      }
    }
  }
};

3. 图片优化

可以使用 image-webpack-loader 来优化图片。 先安装 image-webpack-loadernpm install image-webpack-loader -Dwebpack.config.js 中配置如下:

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/i,
        use: [
          {
            loader: 'image-webpack-loader',
            options: {
              mozjpeg: {
                progressive: true,
                quality: 65
              },
              // optipng.enabled: false will disable optipng
              optipng: {
                enabled: false
              },
              pngquant: {
                quality: [0.65, 0.90],
                speed: 4
              },
              gifsicle: {
                interlaced: false
              },
              // the webp option will enable WEBP
              webp: {
                quality: 75
              }
            }
          }
        ]
      }
    ]
  }
};

4. 移除未使用的 CSS

可以使用 purgecss-webpack-plugin 来移除未使用的 CSS。 先安装 purgecss-webpack-pluginnpm install purgecss-webpack-plugin -Dwebpack.config.js 中配置如下:

const PurgeCSSPlugin = require('purgecss-webpack-plugin');
const glob = require('glob-all');

module.exports = {
  plugins: [
    new PurgeCSSPlugin({
      paths: glob.sync(`${path.join(__dirname, 'src')}/**/*`, {nodir: true}),
      safelist: function () {
        return {
          standard: ['body-dark']
        };
      }
    })
  ]
};