千家信息网

通用webpack多页面自动导入方案是怎么样的

发表于:2025-02-20 作者:千家信息网编辑
千家信息网最后更新 2025年02月20日,这篇文章主要为大家分析了通用webpack多页面自动导入方案是怎么样的的相关知识点,内容详细易懂,操作细节合理,具有一定参考价值。如果感兴趣的话,不妨跟着跟随小编一起来看看,下面跟着小编一起深入学习"
千家信息网最后更新 2025年02月20日通用webpack多页面自动导入方案是怎么样的

这篇文章主要为大家分析了通用webpack多页面自动导入方案是怎么样的的相关知识点,内容详细易懂,操作细节合理,具有一定参考价值。如果感兴趣的话,不妨跟着跟随小编一起来看看,下面跟着小编一起深入学习"通用webpack多页面自动导入方案是怎么样的"的知识吧。

前言

在之前,我写了一个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.tsimport 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.tsconst { entries, htmlPlugins } = getPages('./src/pages/**/*');const config: Configuration = {  mode: 'development',  entry: entries,  // ...  plugins: [    ...htmlPlugins,  ],};

关于"通用webpack多页面自动导入方案是怎么样的"就介绍到这了,更多相关内容可以搜索以前的文章,希望能够帮助大家答疑解惑,请多多支持网站!

0