基於webpack實現多html頁面開發框架四 自動寫入都入口,自動插入多個htmlWebpackPlugin插件

一、解決什麼問題

     1、手寫頁面多入口,一個一個輸入太麻煩,通過代碼實現

     2、手寫多個htmlWebpackPlugin插件太麻煩,通過代碼實現

二、多入口代碼實現

 1 //讀取所有.js文件,動態設置多入口
 2 function getEntry() {
 3     var entry = {};
 4     //讀取src目錄下page下的所有.js文件
 5     glob.sync('./src/pages/**/*.js')
 6         .forEach(function (name) {
 7             let start = name.indexOf('src/') + 10,
 8                 end = name.length - 3;
 9             let n = name.slice(start, end);
10             let key = n.slice(0, n.lastIndexOf('/')); //保存各個組件的入口
11             // console.log(key);
12             entry[key] = name;
13         });
14     return entry;
15 };

  修改module.exports的入口entry,註釋掉原來手寫的代碼,改成上面的方法如下:

  

 

 三、多htmlWebpackPlugin插件代碼實現

 1 //插入htmlWebpackPlugin
 2  (function(){
 3     //取得配置的入口key
 4     const entryObj = getEntry();
 5     //存儲路徑和chunks
 6     const htmlArray = [];
 7     for(let key in entryObj){
 8         htmlArray.push({
 9             html: key,
10             chunks: ['vendor', 'common', key]
11         })
12     }
13     //自動生成html模板
14     htmlArray.forEach((element) => {
15         module.exports.plugins.push(new htmlWebpackPlugin(getHtmlConfig(element.html, element.chunks)));
16     });
17  })();
module.exports.plugins是配置文件當中的plugins數組,getHtmlConfig方法主要是返回htmlWebpackPlugin的配置,代碼如下:
 1 // 設置html-webpack-plugin參數,返回參數對象
 2 let getHtmlConfig = function (name, chunks) {
 3     var _template = `./src/pages/${name}/index.html`;
 4     var _filename = `${name}/index.html`;
 5     //index單獨處理
 6     if (name === "index") {
 7         _filename = `index.html`;
 8     }
 9     let config = {
10         template: _template,
11         filename: _filename,
12         // favicon: './favicon.ico',
13         // title: title,
14         inject: true, //設置爲true插入的元素放入body元素的底部
15         hash: true, //開啓hash  ?[hash]
16         chunks: chunks,
17         minify: process.env.NODE_ENV === "development" ? false : {
18             removeComments: true, //移除HTML中的註釋
19             collapseWhitespace: true, //摺疊空白區域 也就是壓縮代碼
20             removeAttributeQuotes: true, //去除屬性引用
21         }
22     };
23     return config;
24 };

  註釋掉原來module.exports.plugins配置當中手寫的HtmlWebpackPlugin

四、測試

  1、在src中的pages目錄當中新建index2文件夾,下面新建index.js和index.html

      2、運行webpack命令查看效果,如下圖:

  

 

 五、實現思路

  1、入口以文件的目錄爲key,js文件的具體路徑爲值

      2、根據入口文件的key拼接.html文件模板路徑,key直接作爲chunks的值

      3、往module.exports.plugins的數組中插入HtmlWebpackPlugin對象

 

 

源碼地址:https://github.com/James-14/webpack4_multi_page_demo

寫的不對之處請大家批評指正~~~~!!!!!! 

 

文章原創,轉載請註明出處,謝謝!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章