在多页应用(MPA)中使用 Webpack 时,如何优化公共资源的加载,以避免不同页面间重复加载相同的资源?请谈谈具体的方法和实践。

在多页应用(MPA)中使用 Webpack 时,优化公共资源加载是以减少整体加载时间、提高用户访问速度的关键。以下是几种常见且有效的优化方法和实践:

  1. 使用 CommonsChunkPlugin(旧版 Webpack)/ optimization.splitChunks(Webpack 4+)

    • 通过 optimization.splitChunks 配置项,可以将公共模块提取到一个或多个单独的文件中,这样可以在不同页面间共享这些资源,减少重复下载。
    • 示例配置:
    optimization: {
      splitChunks: {
        chunks: 'all', // 对所有类型进行拆分
        minSize: 30000, // 公共模块最小体积
        maxSize: 0, // 单个分包最大体积
        minChunks: 1, // 被引用次数,超过此值的模块会打包到公共片段
        maxAsyncRequests: 5, // 按需加载时并行加载的数量
        maxInitialRequests: 3, // 入口js最大并行请求数
        automaticNameDelimiter: '~', // 打包后的文件名连接符
        name: true, // 使用默认值
        cacheGroups: { // 缓存组,公共代码会被合并进入这些组
          vendor: {
            test: /[\\/]node_modules[\\/]/, // 抽取 node modules 代码
            priority: -10, // 优先级
          },
          default: {
            minChunks: 2, // 默认配置
            priority: -20,
            reuseExistingChunk: true, // 默认配置
          },
        },
      },
    }
    
  2. 利用 DllPlugin 和 DllReferencePlugin

    • DllPlugin 可以在编译时将第三方库(如 React, Vue 等)打包成一个单独的 DLL 文件,DllReferencePlugin 则在主项目中引用这个 DLL 文件。这种方法可以显著减少捆绑时间,特别是在开发模式下。
    • 示例配置:
    // webpack.dll.config.js
    const path = require('path');
    const webpack = require('webpack');
    
    module.exports = {
      entry: {
        vendor: ['react', 'react-dom'],
      },
      output: {
        path: path.join(__dirname, 'dist'),
        filename: '[name].dll.js',
        library: '[name]',
      },
      plugins: [
        new webpack.DllPlugin({
          path: path.join(__dirname, 'dist', '[name]-manifest.json'),
          name: '[name]',
        }),
      ],
    };
    
    // webpack.config.js
    module.exports = {
      // ... 其他配置
      plugins: [
        new webpack.DllReferencePlugin({
          manifest: require('./dist/vendor-manifest.json'),
        }),
      ],
    };
    
  3. 懒加载(按需加载)

    • 懒加载是一种提高首屏加载速度的技术,可以确保用户在最初访问页面时只加载必要的资源,其他非必要资源则在需要时再加载。
    • 示例代码:
    function importComponent(name) {
      return () => import(`./components/${name}`);
    }
    
    // 使用 React 路由时
    const Routes = [
      { path: '/', component: importComponent('Home') },
      { path: '/about', component: importComponent('About') },
    ];
    

通过结合使用上述技术,可以在多页应用中有效地管理和优化公共资源的加载,从而提升用户体验和性能。