Webpack 多页面应用打包方案

Webpack 作为模块打包工具,在 JavaScript 开发中广泛应用。针对包含多个独立 HTML 页面的项目,单页应用打包方式不再适用。将探讨使用 Webpack 实现多页面应用的构建。

配置基础

Webpack 核心在于配置文件 webpack.config.js。多页面打包中,需要配置多个入口点,对应各个页面入口文件。如:

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

module.exports = {
  entry: {
    page1: './src/page1/index.js',
    page2: './src/page2/index.js',
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].bundle.js',
  },
  // ...
};

使用 HtmlWebpackPlugin

HtmlWebpackPlugin 自动生成 HTML 文件,并插入打包后的 JavaScript 文件。针对每个页面,需创建一个插件实例:

const htmlPlugins = [
  new HtmlWebpackPlugin({
    filename: 'page1.html',
    template: './src/page1/index.html',
    chunks: ['page1'],
  }),
  new HtmlWebpackPlugin({
    filename: 'page2.html',
    template: './src/page2/index.html',
    chunks: ['page2'],
  }),
];

优势

多页面打包方案优势如下:

  • 分离页面资源,提高加载效率
  • 灵活控制页面内容,利于后期维护和扩展
  • 适用于复杂多页面的应用场景
zip 文件大小:5.44KB