淺談webpack+react多頁面開發(fā)終極架構(gòu)
webpack在單頁面打包上應(yīng)用廣泛,以create-react-app為首的腳手架眾多,單頁面打包通常指的是將業(yè)務(wù)js,css打包到同一個(gè)html文件中,整個(gè)項(xiàng)目只有一個(gè)html文件入口,但也有許多業(yè)務(wù)需要多個(gè)頁面不同的入口,比如不同的h5活動(dòng),或者需要支持seo的官方網(wǎng)站,都需要多個(gè)不同的html。webpack-react-multi-page架構(gòu)讓你可以在多頁面在項(xiàng)目開發(fā)中自動(dòng)化打包新創(chuàng)建頁面并保證每個(gè)頁面都可以熱更新 ,build打包后有清晰的文件層次結(jié)構(gòu)。
概覽
| key | value |
|---|---|
| 名稱 | webpack+react多頁面架構(gòu) |
| 描述 | 簡單易用的多頁面自動(dòng)化開發(fā)架構(gòu) |
| 開發(fā)者 | leinov |
| 發(fā)布日期 | 2018-11-07 |
| 版本 | 2.0 |
| 倉庫 | github地址 |
特性
- 支持多頁面同時(shí)熱加載開發(fā)
- 自動(dòng)識(shí)別新創(chuàng)建頁面
- 每個(gè)頁面生成個(gè)性化信息
- 分類打包
- 靈活擴(kuò)展
安裝&使用
// clone git clone git@github.com:leinov/webpack-react-multi-page.git // 安裝依賴包 npm install // 開發(fā) npm run dev // 編譯打包 npm run build // 啟動(dòng)生產(chǎn)頁面 npm start
新創(chuàng)建頁面在src下添加文件夾并創(chuàng)建pageinfo.json 然后npm run dev 即可
|-- src
|-- index/
|-- page2/
|-- index.js
|-- pageinfo.json
項(xiàng)目架構(gòu)
技術(shù)使用
- react16
- webpack4
- html-webpack-plugin 生成html文件
- mini-css-extract-plugin css分離打包
- uglifyjs-webpack-plugin js壓縮
- optimize-css-assets-webpack-plugin css壓縮
- es6
- babel
- node
- opn 打開瀏覽器
- compression 開啟gzip壓縮
- express
- fs
- git
目錄結(jié)構(gòu)
|-- webpack-react-multi-pages //項(xiàng)目
|-- dist //編譯生產(chǎn)目錄
|-- index
|-- index.css
|-- index.js
|-- about
|-- about.css
|-- about.js
|-- images
|-- index.html
|-- about.html
|-- node_modules //node包
|-- src //開發(fā)目錄
|-- index //index頁面打包入口
|-- images/
|-- js
|-- app.js// 業(yè)務(wù)js
|-- index.sass
|-- index.js //頁面js入口
|-- about //about頁面打包入口
|-- images/
|--js
|-- app.js// 業(yè)務(wù)js
|-- about.sass
|-- about.js //頁面js入口
|-- template.html // html模板
|-- style.sass //公共sass
|-- webpackConfig //在webpack中使用
|-- getEntry.js //獲取入口
|-- getFilepath.js //src下需要打包頁面文件夾
|-- htmlconfig.js //每個(gè)頁面html注入數(shù)據(jù)
|-- package.json
|-- .gitignore
|-- webpack.config.js //webpack配置文件
|-- www.js //生產(chǎn)啟動(dòng)程序
wiki
webpack打包單頁面應(yīng)用
webpack在單頁面打包上應(yīng)用廣泛,以create-react-app為首的接觸腳手架眾多,單頁面打包通常指的是將業(yè)務(wù)js,css打包到同一個(gè)html文件中,整個(gè)項(xiàng)目只有一個(gè)html文件入口
webpack單頁面打包配置
webpack.config.js
module.exports = (env, argv) => ({
entry: ".src/index.js",
output: {
path: path.join(__dirname, "dist"),
filename: "bundle.js"
},
module: {
rules: [
...
],
},
plugins: [
new HtmlWebpackPlugin({
title: "首頁",
filename:"index.html",
favicon:"",
template: "./src/template.html",
})
]
});
這樣就可以在dist文件夾下打包出一個(gè)下面這樣的文件
<!DOCTYPE html>
<html lang="en">
<head>
<title>首頁</title>
<body>
<div id="root"></div>
<script type="text/javascript" src="bundle.js"></script></body>
</html>
webpack多頁面打包配置
webpack 的entry支持兩種種格式
打包單個(gè)文件
module.exports = {
entry: '.src/file.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
};
這樣就會(huì)在dist下打包出一個(gè)bundle.js
打包出多個(gè)文件
module.exports = {
entry: {
index:"./src/index.js",
about:"./src/about.js"
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js' index.js,about.js這兩個(gè)文件
}
};
上面在dist下打包出兩個(gè)與entry屬性名對(duì)應(yīng)的js文件
將每個(gè)js掛載到相應(yīng)的html文件上
這里我們需要用到html-webpack-plugin這個(gè)webpack插件,每添加一個(gè)頁面就需要在plugins添加一個(gè)new HtmlWebpackPlugin({....})
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = (env, argv) => ({
entry: {
index:"./src/index.js",
about:"./src/about.js"
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js' index.js,about.js這兩個(gè)文件
}
....//其他配置
plugins: [
new HtmlWebpackPlugin(
{
filename:"index.html",//生成的index.html
template: "./src/template.html",}) //模板
chunks:["index"]
}),
new HtmlWebpackPlugin(
{
filename:"about.html",//生成的index.html
template: "./src/template.html",}) //模板
chunks:["index"]
})
]
})
html-webpack-plugin 會(huì)通過 template.html 模板生成對(duì)應(yīng)的filename名的html文件,并一并打包到output中對(duì)應(yīng)的文件夾下,注意,在沒有特殊配置的情況下所有打包的文件都是對(duì)應(yīng)到output中 path 這個(gè)目錄下,也包括html。這里的 chunks 需要注意,它是確定該html需要引入哪個(gè)js,如果沒寫的話,默認(rèn)會(huì)引出所有打包的js,當(dāng)然這不是我們想要的。
上面的配置最終可以在dist下打包出下面的文件結(jié)構(gòu)
|-- dist |-- index.js |-- about.js |-- index.html //內(nèi)掛載index.js |-- about.html //內(nèi)掛載about.js
通過上面這樣的配置,再加上devServer,我們已經(jīng)可以實(shí)現(xiàn)多頁面的配置開發(fā)了,但這樣很不智能,因?yàn)槟忝吭黾右粋€(gè)頁面,就要在wepback里面配置一次,會(huì)非常繁瑣,所以我們來優(yōu)化下,讓我們只專注于開發(fā)頁面,配置交給webpack自己.
webpack多頁面配置優(yōu)化
我們?cè)倏聪聅rc下面的文件結(jié)構(gòu)
|-- src
|-- index
|-- app.js
|-- index.scss
|-- index.js
|-- about
|-- app.js
|-- index.scss
|-- index.js
src下面每個(gè)文件夾對(duì)應(yīng)一個(gè)html頁面的js業(yè)務(wù),如果我們直接把文件夾對(duì)應(yīng)入口js找到并把他們合并生成對(duì)應(yīng)的entry,那是不是就不用手動(dòng)寫entry了呢,是的!
遍歷文件目錄
/* eslint-env node */
/**
* @file: getFilePath.js 遍歷文件目錄
* @author: leinov
* @date: 2018-10-11
*/
const fs = require("fs");
/**
* 【遍歷某文件下的文件目錄】
*
* @param {String} path 路徑
* @returns {Array} ["about","index"]
*/
module.exports = function getFilePath(path){
let fileArr = [];
let existpath = fs.existsSync(path); //是否存在目錄
if(existpath){
let readdirSync = fs.readdirSync(path); //獲取目錄下所有文件
readdirSync.map((item)=>{
let currentPath = path + "/" + item;
let isDirector = fs.statSync(currentPath).isDirectory(); //判斷是不是一個(gè)文件夾
if(isDirector && item !== "component"){ // component目錄下為組件 需要排除
fileArr.push(item);
}
});
return fileArr;
}
};
比如在src下有index頁面項(xiàng)目,about項(xiàng)目 遍歷結(jié)果為["index","about"];
遍歷生成打包入口數(shù)組
/* eslint-env node */
/**
* @file: getEntry.js 獲取entry文件入口
* @author: leinov
* @date: 2018-10-11
* @update: 2018-11-04 優(yōu)化入口方法 調(diào)用getFilePath
*/
const getFilePath = require("./getFilepath");
/**
* 【獲取entry文件入口】
*
* @param {String} path 引入根路徑
* @returns {Object} 返回的entry { "about/aoubt":"./src/about/about.js",...}
*/
module.exports = function getEnty(path){
let entry = {};
getFilePath(path).map((item)=>{
/**
* 下面輸出格式為{"about/about":"./src/aobout/index.js"}
* 這樣目的是為了將js打包到對(duì)應(yīng)的文件夾下
*/
entry[`${item}/${item}`] = `${path}/${item}/index.js`;
});
return entry;
};
這里我們使用getFilepath獲取的數(shù)組,在獲取到每個(gè)目錄下的js文件,組合成一個(gè)js入口文件的如下格式的對(duì)象。
{
"index/index":"./src/index/index.js",
"about/about":"./src/about/index.js"
}
在webpack中使用getEntry
const getEntry = require("./webpackConfig/getEntry");
const entry = getEntry();
module.exports = (env, argv) => ({
entry: entry,
})
這樣我們就自動(dòng)獲取到了entry
html-webpack-plugin自動(dòng)配置
因?yàn)槊總€(gè)頁面都需要配置一個(gè)html,而且每個(gè)頁面的標(biāo)題,關(guān)鍵字,描述等信息可能不同,所以我們?cè)诿總€(gè)頁面文件夾下創(chuàng)建一個(gè)pageinfo.json,通過fs模塊獲取到j(luò)son里信息再遍歷到對(duì)應(yīng)得html-webpack-plugin中生成一個(gè)html插件數(shù)組。
index/pageinfo.json 生成index.html頁面信息
{
"title":"首頁",
"keywords":"webpack多頁面"
}
about/pageinfo.json 生成about.html頁面信息供
{
"title":"關(guān)于頁面",
"keywords":"webpack多頁面關(guān)于頁面"
}
通過fs遍歷讀取并生成HtmlWebpackPlugin數(shù)組供webpack使用
遍歷html插件數(shù)組
/**
* @file htmlconfig.js 頁面html配置
* @author:leinov
* @date: 2018-10-09
* @update: 2018-11-05
* @use: 動(dòng)態(tài)配置html頁面,獲取src下每個(gè)文件下的pageinfo.json內(nèi)容,解析到HtmlWebpackPlugin中
*/
const fs = require("fs");
const HtmlWebpackPlugin = require("html-webpack-plugin");//生成html文件
const getFilePath = require("./getFilepath");
let htmlArr = [];
getFilePath("./src").map((item)=>{
let infoJson ={},infoData={};
try{
// 讀取pageinfo.json文件內(nèi)容,如果在頁面目錄下沒有找到pageinfo.json 捕獲異常
infoJson = fs.readFileSync(`src/${item}/pageinfo.json`,"utf-8");//
infoData = JSON.parse(infoJson);
}catch(err){
infoData = {};
}
htmlArr.push(new HtmlWebpackPlugin({
title:infoData.title ? infoData.title : "webpack,react多頁面架構(gòu)",
meta:{
keywords: infoData.keywords ? infoData.keywords : "webpack,react,github",
description:infoData.description ? infoData.description : "這是一個(gè)webpack,react多頁面架構(gòu)"
},
chunks:[`${item}/${item}`], //引入的js
template: "./src/template.html",
filename : item == "index" ? "index.html" : `${item}/index.html`, //html位置
minify:{//壓縮html
collapseWhitespace: true,
preserveLineBreaks: true
},
}));
});
module.exports = htmlArr;
wbpack終極配置
const path = require("path");
const getEntry = require("./webpackConfig/getEntry"); //入口配置
const entry = getEntry("./src");
const htmlArr =require("./webpackConfig/htmlConfig");// html配置
module.exports = (env, argv) => ({
entry: entry
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
}
....//其他配置
devServer: {
port: 3100,
open: true,
},
plugins: [
...htmlArr
]
})
這樣一個(gè)自動(dòng)化完整的多頁面架構(gòu)配置就完成了,如果我們要新創(chuàng)建一個(gè)頁面
1.在src下創(chuàng)建一個(gè)文件目錄
2.在新創(chuàng)建的文件目錄下添加index.js(必須,因?yàn)槭莣ebpack打包入口文件)
3.在新創(chuàng)建文件夾下添加pageinfo.json(非必須) 供html插件使用
4.npm run dev開發(fā)
完整代碼參考項(xiàng)目code
版本
| 版本 | 日期 | 分支 | 備注 |
|---|---|---|---|
| 2.0 | 2018-11-08 | master |
優(yōu)化html插件自動(dòng)化 |
| 1.0 | 2018-10-07 | version1.0 |
第一版 |
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
react render props模式實(shí)現(xiàn)組件復(fù)用示例
本文主要介紹了react render props模式實(shí)現(xiàn)組件復(fù)用示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
React工作流程及Error Boundaries實(shí)現(xiàn)過程講解
這篇文章主要介紹了React工作流程及Error Boundaries實(shí)現(xiàn)過程講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-02-02
React將組件作為參數(shù)進(jìn)行傳遞的3種方法實(shí)例
其實(shí)react組件之間傳遞參數(shù)是比較簡單的,組件傳入?yún)?shù)的一種方式,下面這篇文章主要給大家介紹了關(guān)于React將組件作為參數(shù)進(jìn)行傳遞的3種方法,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07
如何應(yīng)用?SOLID?原則在?React?中整理代碼之開閉原則
React?不是面向?qū)ο?,但這些原則背后的主要思想可能是有幫助的,在本文中,我將嘗試演示如何應(yīng)用這些原則來編寫更好的代碼,對(duì)React?SOLID原則開閉原則相關(guān)知識(shí)感興趣的朋友一起看看吧2022-07-07
react PropTypes校驗(yàn)傳遞的值操作示例
這篇文章主要介紹了react PropTypes校驗(yàn)傳遞的值操作,結(jié)合實(shí)例形式分析了react PropTypes針對(duì)傳遞的值進(jìn)行校驗(yàn)操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2020-04-04
React18的useEffect執(zhí)行兩次如何應(yīng)對(duì)
這篇文章主要給大家介紹了關(guān)于React18的useEffect執(zhí)行兩次如何應(yīng)對(duì)的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用React具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07

