目录
  • 前言
  • 思考
  • 安装glob
  • 创建工具类
  • getentry
  • gethtmlwebpackplugin
  • 二次封装
  • 应用

前言

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

思考

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

安装glob

pnpm add glob

创建工具类

在src目录下创建uilts/index.ts文件,引入所需的依赖包(glob、path、html-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,
  ],
};

到此这篇关于详解通用webpack多页面自动导入方案的文章就介绍到这了,更多相关webpack多页面自动导入内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!