likes
comments
collection
share

webpack 完全指南:多页面应用打包方案(MPA)

作者站长头像
站长
· 阅读数 80

什么是多页面应用(MPA)

多页面应用程序,顾名思义是存在多个入口,每个业务都有自己的页面。每一次页面跳转的时候,server 会拉取一个新的 HTML 文档返回给客户端,页面重新加载此新文档,并且资源被重新下载。

多页面应用有什么优点呢?

  • 页面之间是相互解耦的。
  • 搜索引擎是可以识别 html 内容的,而 MPA 的每个页面所有的内容都放在 Html 中,所以对 SEO 更友好。

多页面应用的缺点也很显然,因为每次跳转都需要发出一个 http 请求,势必会影响页面切换速度,对网络速度慢的用户不友好。

多页面应用的打包

entry

我们的多页面应用有 n 个入口,在 webpac 中就要配置 n 个单独的入口点,也就是 n 个独立分离的依赖图:

// webapck.config.js

module.exports = {
  entry: {
    pageOne: "./src/pageOne/index.js",
    pageTwo: "./src/pageTwo/index.js",
    pageThree: "./src/pageThree/index.js",
  },
  // ...
};

html-webpack-plugin

我们的多页面应用有 n 个入口,也需要对应 n 个 html-webpack-plugin:

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

module.exports = {
  entry: {
    pageOne: "./src/pageOne/index.js",
    pageTwo: "./src/pageTwo/index.js",
    pageThree: "./src/pageThree/index.js",
  },
  // ...
  plugins: [
    new HtmlWebpackPlugin({
      template: path.join(__dirname, "src/pageOne.html"),
      filename: "pageOne.html",
      chunks: ["pageOne"],
    }),
    new HtmlWebpackPlugin({
      template: path.join(__dirname, "src/pageTwo.html"),
      filename: "pageTwo.html",
      chunks: ["pageTwo"],
    }),
    new HtmlWebpackPlugin({
      template: path.join(__dirname, "src/pageThree.html"),
      filename: "pageThree.html",
      chunks: ["pageThree"],
    }),
  ],
};

glob

当我们的多页面应用发生页面的增减时,都需要手动修改 webpack 中的 entry / html-webpack-plugin 配置。这显然不符合程序的思维咯,那有没有更解放的方法呢?

glob 利用文件的统配匹配的原理,根据一定的 pattern 匹配文件,我们再根据匹配的文件去动态获取 entry 和设置 html-webpack-plugin 的数量。

准备工作

在开始配置之前,需要先规范我们的文件存放规则,我们可以约定把入口文件放在 src 下的一级文件夹中的 index.js

webpack 完全指南:多页面应用打包方案(MPA)

动态生成

安装 glob

npm i glob -D

接下来,配置动态生成 entryhtml-webpack-plugin

// webapck.config.js
const path = require("path");
const glob = require("glob");

const setMPA = () => {
  const entry = {};
  const htmlWebpackPlugins = [];
  const entryFiles = glob.sync(path.resolve(__dirname, "src/*/index.js"));
  entryFiles.map((file) => {
    const match = file.match(/\/src\/(.*)\/index.js/);
    const pageName = match && match[1];
    entry[pageName] = file;
    htmlWebpackPlugins.push(
      new HtmlWebpackPlugin({
        template: path.join(__dirname, `src/${pageName}/index.html`),
        filename: `${pageName}.html`, // 输出文件名
        chunks: [pageName],
      })
    );
  });
  return { entry, htmlWebpackPlugins };
};

const { entry, htmlWebpackPlugins } = setMPA();

module.exports = {
  entry,
  plugins: [
    // ...
    ...htmlWebpackPlugins,
  ],
  // ...
};

打包

npm run build 后,你应该看到的打包效果:

webpack 完全指南:多页面应用打包方案(MPA)

webpack 系列

转载自:https://juejin.cn/post/7033338362924974087
评论
请登录