Building multi page programs using webpack

Time:2021-7-28

It is very common to use webpack to build single page programs, but we may need to develop multi page programs in actual development. Therefore, I studied how to use webpack to build multi page programs.

principle

Consider the folder where each page is located as a separate single page program directory, and configure multiple foldersentryas well ashtml-webpack-pluginMulti page packaging can be realized.

The following is the directory structure of the project

.
├─ src
│  └─ pages
│       ├─ about
│       │    ├─ index.css
│       │    ├─ index.html
│       │    └─ index.js
│       └─ index
│            ├─ index.css
│            ├─ index.html
│            └─ index.js
└─ webpack.config.js

Single page packaging basic configuration

First, let’s take a look at the basic configuration of webpack for single page programs

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

module.exports = {
  entry: './src/index.js',
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      filename: 'index.html',
    }),
  ],
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'bundle.js',
  },
};

If you want to change it into a multi page program, you need to change its single entry and single HTML template to multi entry and multi HTML template

Multi page packaging basic configuration

Transformation entrance

The traditional multi entry method can be written in the form of key value pairs

module.exports = {
  entry: {
    index: './src/pages/index/index.js',
    about: './src/pages/about/index.js',
  },
  ...
}

In this way, it is troublesome to manually add an entry for each additional page, so we can define a function to generate an entry according to the directory to simplify our operation

const glob = require('glob');

function getEntry() {
  const entry = {};
  glob.sync('./src/pages/**/index.js').forEach((file) => {
    const name = file.match(/\/pages\/(.+)\/index.js/)[1];
    entry[name] = file;
  });
  return entry;
}

module.exports = {
  entry: getEntry(),
  ...
}

Transformation output

In the output configuration item, it is no longer appropriate to write the output file name to display, so we need to change the name to match the source file

module.exports = {
  ...
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'js/[name].[contenthash].js',
  },
  ...
}

Configure multiple HTML webpack plugins

Like the portal, different HTML templates can be written directly into the plug-in configuration. Here, we need to configure different HTML templates for each plug-inchunksTo prevent JS from being injected into wrong HTML

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

module.exports = {
  ...
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/pages/index/index.html',
      chunks: ['index'],
      filename: 'index.html',
    }),
    new HtmlWebpackPlugin({
      template: './src/pages/about/index.html',
      chunks: ['about'],
      filename: 'about.html',
    }),
  ],
  ...
};

This approach has the same problem as the entry, so we define a function to generate this configuration

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

function getHtmlTemplate() {
  return glob
    .sync('./src/pages/**/index.html')
    .map((file) => {
      return { name: file.match(/\/pages\/(.+)\/index.html/)[1], path: file };
    })
    .map(
      (template) =>
        new HtmlWebpackPlugin({
          template: template.path,
          chunks: [template.name.toString()],
          filename: `${template.name}.html`,
        })
    );
}

module.exports = {
  ...
  plugins: [...getHtmlTemplate()],
  ...
};

The configuration of such a simple multi page project is completed. We can also add heating update, code segmentation and other functions on this basis. Those who are interested can try it by themselves

Full configuration

Project address:xmy6364/webpack-multipage

// webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const glob = require('glob');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

//Multi page entry
function getEntry() {
  const entry = {};
  glob.sync('./src/pages/**/index.js').forEach((file) => {
    const name = file.match(/\/pages\/(.+)\/index.js/)[1];
    entry[name] = file;
  });
  return entry;
}

//Multi page template
function getHtmlTemplate() {
  return glob
    .sync('./src/pages/**/index.html')
    .map((file) => {
      return { name: file.match(/\/pages\/(.+)\/index.html/)[1], path: file };
    })
    .map(
      (template) =>
        new HtmlWebpackPlugin({
          template: template.path,
          chunks: [template.name.toString()],
          filename: `${template.name}.html`,
        })
    );
}

const config = {
  mode: 'production',
  entry: getEntry(),
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'js/[name].[contenthash].js',
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
  plugins: [new CleanWebpackPlugin(), ...getHtmlTemplate()],
  devServer: {
    contentBase: path.join(__dirname, 'dist'),
    compress: true,
    port: 3000,
    hot: true,
    open: true,
  },
};

module.exports = config;

Recommended Today

VBS obtains the operating system and its version number

VBS obtains the operating system and its version number ? 1 2 3 4 5 6 7 8 9 10 11 12 ‘************************************** ‘*by r05e ‘* operating system and its version number ‘************************************** strComputer = “.” Set objWMIService = GetObject(“winmgmts:” _  & “{impersonationLevel=impersonate}!\\” & strComputer & “\root\cimv2”) Set colOperatingSystems = objWMIService.ExecQuery _  (“Select * from […]