欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解通用webpack多頁面自動導(dǎo)入方案

 更新時間:2022年01月23日 09:25:30   作者:_island  
本文主要介紹了通用webpack多頁面自動導(dǎo)入方案,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下

前言

在之前,我寫了一個webpack的模板。在平時我寫栗子或者是寫幾個頁面的時候會用到它。當(dāng)這個模板需要多個頁面時需要手動到webpack.config.ts文件中配置entry和HtmlWebpackPlugin,有點麻煩。

思考

我們項目中的頁面都是存放在src/pages/*.html中的,我們可以搜索這里文件夾下的html文件我們可以利用node中的glob包中的.sync方法,用來匹配搜索我們想要的文件。將匹配到的文件名自動生成一個entrys對象賦值到webpack.config.ts文件中的entry屬性即可。HtmlWebpackPlugin同理。

安裝glob

pnpm add glob

創(chuàng)建工具類

在src目錄下創(chuàng)建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方法,用于搜索頁面所引入的腳本文件,該方法需要傳入一個匹配規(guī)則也就是路徑,使用glob包中的.sync方法進行搜索,該方法返回匹配到的數(shù)據(jù)集。將獲獎到的文件名稱及路徑拼接成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對象。它同樣傳入一個匹配規(guī)則,匹配所有*.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函數(shù).,到時候在webpack.config.ts中調(diào)用它就可以直接拿到entry對象和htmlPlugins數(shù)組。

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,
? };
}

應(yīng)用

在webpack.config.ts中使用getPages函數(shù)。
引入getPages函數(shù),傳入項目中頁面所在的路徑。使用ES6的解構(gòu)獲獎返回的數(shù)據(jù)對象。

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

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

到此這篇關(guān)于詳解通用webpack多頁面自動導(dǎo)入方案的文章就介紹到這了,更多相關(guān)webpack多頁面自動導(dǎo)入內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論