在使用webpack打包多页面应用时,如何合理配置公共代码抽离和按需加载,以达到最优的加载性能?请给出具体的配置示例。

在使用Webpack打包多页面应用时,合理配置公共代码抽离和按需加载是优化加载性能的关键。以下是一个具体的配置示例,展示了如何通过使用 optimization.splitChunks 和 dynamic imports 来实现这些目标。

1. 安装必要的依赖

首先,确保你的项目中安装了 webpack 和 html-webpack-plugin:

npm install --save-dev webpack webpack-cli html-webpack-plugin

2. 配置 webpack.config.js

在 webpack.config.js 中,配置多个入口点和 optimization.splitChunks 以实现公共代码抽离:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: {
    page1: './src/page1/index.js',
    page2: './src/page2/index.js',
  },
  output: {
    filename: '[name].[contenthash].js',
    path: path.resolve(__dirname, 'dist'),
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          priority: 10,
        },
        common: {
          minSize: 0,
          minChunks: 2,
          name: 'common',
          reuseExistingChunk: true,
        },
      },
    },
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/page1/index.html',
      filename: 'page1.html',
      chunks: ['page1', 'vendors', 'common'],
    }),
    new HtmlWebpackPlugin({
      template: './src/page2/index.html',
      filename: 'page2.html',
      chunks: ['page2', 'vendors', 'common'],
    }),
  ],
};

3. 使用动态导入(Dynamic Imports)

在你的页面代码中,使用动态导入来实现按需加载。例如,在 page1/index.js 中:

import('./components/header.js').then((module) => {
  module.default();
});

import('./components/footer.js').then((module) => {
  module.default();
});

4. 运行 Webpack

最后,运行 Webpack 进行打包:

npx webpack

解释

  • 入口配置:定义了两个入口点 page1 和 page2,每个入口点对应一个页面。
  • 输出配置:指定了输出文件的名称和路径,使用 [contenthash] 以便在文件内容发生变化时自动更新文件名,防止缓存问题。
  • 代码分割:optimization.splitChunks 配置用于将公共代码和第三方库分离。vendor 缓存组用于将 node_modules 中的模块进行分割,common 缓存组用于将多个页面中共享的代码进行分割。
  • HtmlWebpackPlugin:为每个页面生成一个 HTML 文件,并指定需要引入的脚本文件。
  • 动态导入:在页面代码中使用 import() 函数进行按需加载,可以有效减少初始加载时间。

通过以上配置,可以实现多页面应用的公共代码抽离和按需加载,从而优化加载性能。