詳解通用webpack多頁面自動匯入方案
目錄
- 前言
- 思考
- 安裝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(gwww.cppcns.comlobPath: 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(http://www.cppcns.com'./src/pages/**/*'); const config: Configuration = { mode: 'development',entry: entries,// ... plugins: [ ...htmlPlugins,],};
到此這篇關於詳解通用webpack多頁面自動匯入方案的文章就介紹到這了,更多相關webpack多頁面http://www.cppcns.com自動匯入內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!