通用webpack多页面自动导入方案

「这是我参与2022首次更文挑战的第5天,活动详情查看:2022首次更文挑战

前言

在之前,我写了一个webpack的模板。在平时我写栗子或者是写几个页面的时候会用到它。当这个模板需要多个页面时需要手动到webpack.config.ts文件中配置entryHtmlWebpackPlugin,有点麻烦。

思考

我们项目中的页面都是存放在src/pages/*.html中的,我们可以搜索这里文件夹下的html文件我们可以利用node中的glob包中的.sync方法,用来匹配搜索我们想要的文件。将匹配到的文件名自动生成一个entrys对象赋值到webpack.config.ts文件中的entry属性即可。HtmlWebpackPlugin同理。

安装glob

pnpm add glob
复制代码

创建工具类

src目录下创建uilts/index.ts文件,引入所需的依赖包(globpathhtml-webpack-plugin)。

src
  └─uilts
  	└─index.ts
复制代码
// uilts/index.ts
import Glob from 'glob';
import path from 'path';
import HtmlWebpackPlugin from 'html-webpack-plugin';
复制代码

getEntry

封装getEntry方法,用于搜索页面所引入的脚本文件,该方法需要传入一个匹配规则也就是路径,使用glob包中的.sync方法进行搜索,该方法返回匹配到的数据集。将获奖到的文件名称及路径拼接成entry对象所需的key:value即可,最终getEntry返回一个对象。

export function getEntry(globPath: string): entryObj {
  const entries: entryObj = { main: './src/main.ts' };
  Glob.sync(`${globPath}.ts`).forEach((entry: string) => {
    const basename: string = path.basename(entry, path.extname(entry));
    const pathname: string = path.dirname(entry);
    entries[basename] = `${pathname}/${basename}`;
  });
  return entries;
}
复制代码

getHtmlWebpackPlugin

封装getHtmlWebpackPlugin方法,用于输出所有匹配到的HtmlWebpackPlugin对象。它同样传入一个匹配规则,匹配所有*.html文件,

export function getHtmlWebpackPlugin(globPath: string): HtmlWebpackPlugin[] {
  const htmlPlugins: HtmlWebpackPlugin[] = [];
  Glob.sync(`${globPath}.html`).forEach((entry: string) => {
    const basename: string = path.basename(entry, path.extname(entry));
    const pathname: string = path.dirname(entry);
    htmlPlugins.push(new HtmlWebpackPlugin({
      title: basename,
      filename: `${basename}.html`,
      template: `${pathname}/${basename}.html`,
      chunks: [basename, 'main'],
      minify: true,
    }));
  });
  return htmlPlugins;
}
复制代码

二次封装

有了这两个方法之后,在把两个方法再封装成getPages函数.,到时候在webpack.config.ts中调用它就可以直接拿到entry对象和htmlPlugins数组。

interface getPagesType {
  entries: entryObj,
  htmlPlugins: HtmlWebpackPlugin[]
}

export function getPages(pagePath: string): getPagesType {
  const entries: entryObj = getEntry(pagePath);
  const htmlPlugins: HtmlWebpackPlugin[] = getHtmlWebpackPlugin(pagePath);
  return {
    entries,
    htmlPlugins,
  };
}
复制代码

应用

webpack.config.ts中使用getPages函数。

引入getPages函数,传入项目中页面所在的路径。使用ES6的解构获奖返回的数据对象。

// webpack.config.ts
const { entries, htmlPlugins } = getPages('./src/pages/**/*');

const config: Configuration = {
  mode: 'development',
  entry: entries,
  // ...
  plugins: [
    ...htmlPlugins,
  ],
};
复制代码

image-20220122161150279

image-20220122161054056

猜你喜欢

转载自juejin.im/post/7055941374687838216
今日推荐