日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

webpack+react多页面开发架构

發布時間:2025/6/17 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 webpack+react多页面开发架构 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

項目已經升級為最新版本參考react-multi-page-app

webpack在單頁面打包上應用廣泛,以create-react-app為首的腳手架眾多,單頁面打包通常指的是將業務js,css打包到同一個html文件中,整個項目只有一個html文件入口,但也有許多業務需要多個頁面不同的入口,比如不同的h5活動,或者需要支持seo的官方網站,都需要多個不同的htmlwebpack-react-multi-page架構讓你可以在多頁面在項目開發中自動化打包新創建頁面并保證每個頁面都可以熱更新 ,build打包后有清晰的文件層次結構。

概覽

keyvalue
名稱webpack+react多頁面架構
描述簡單易用的多頁面自動化開發架構
開發者leinov
發布日期2018-11-07
版本2.0
倉庫github地址

特性

  • ??????? 支持多頁面同時熱加載開發
  • ? 自動識別新創建頁面
  • ? 每個頁面生成個性化信息
  • ? 分類打包
  • ? 靈活擴展

安裝&使用

// clone git clone git@github.com:leinov/react-multi-page-app.git// 安裝依賴包 npm install// 開發 npm run dev// 編譯打包 npm run build// 啟動生產頁面 npm start

新創建頁面在src下添加文件夾并創建pageinfo.json 然后npm run dev 即可

|-- src|-- index/|-- page2/|-- index.js|-- pageinfo.json

項目架構

技術使用

  • 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

目錄結構

|-- webpack-react-multi-pages //項目|-- dist //編譯生產目錄|-- index|-- index.css|-- index.js|-- about|-- about.css|-- about.js|-- images|-- index.html|-- about.html|-- node_modules //node包|-- src //開發目錄|-- index //index頁面打包入口|-- images/|-- js|-- app.js// 業務js|-- index.sass|-- index.js //頁面js入口|-- about //about頁面打包入口|-- images/|--js|-- app.js// 業務js|-- about.sass|-- about.js //頁面js入口|-- template.html // html模板|-- style.sass //公共sass|-- webpackConfig //在webpack中使用|-- getEntry.js //獲取入口|-- getFilepath.js //src下需要打包頁面文件夾|-- htmlconfig.js //每個頁面html注入數據|-- package.json|-- .gitignore|-- webpack.config.js //webpack配置文件|-- www.js //生產啟動程序

wiki

webpack打包單頁面應用

webpack在單頁面打包上應用廣泛,以create-react-app為首的接觸腳手架眾多,單頁面打包通常指的是將業務js,css打包到同一個html文件中,整個項目只有一個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文件夾下打包出一個下面這樣的文件

<!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支持兩種種格式

打包單個文件

module.exports = {entry: '.src/file.js',output: {path: path.resolve(__dirname, 'dist'),filename: 'bundle.js'} };

這樣就會在dist下打包出一個bundle.js

打包出多個文件

module.exports = {entry: {index:"./src/index.js",about:"./src/about.js"},output: {path: path.resolve(__dirname, 'dist'),filename: '[name].js' index.js,about.js這兩個文件} };

上面在dist下打包出兩個與entry屬性名對應的js文件

將每個js掛載到相應的html文件上

這里我們需要用到html-webpack-plugin這個webpack插件,每添加一個頁面就需要在plugins添加一個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這兩個文件}....//其他配置plugins: [new HtmlWebpackPlugin({filename:"index.html",//生成的index.htmltemplate: "./src/template.html",}) //模板chunks:["index"]}),new HtmlWebpackPlugin({filename:"about.html",//生成的index.htmltemplate: "./src/template.html",}) //模板chunks:["index"]})] })

html-webpack-plugin 會通過 template.html 模板生成對應的filename名的html文件,并一并打包到output中對應的文件夾下,注意,在沒有特殊配置的情況下所有打包的文件都是對應到output中 path 這個目錄下,也包括html。這里的 chunks 需要注意,它是確定該html需要引入哪個js,如果沒寫的話,默認會引出所有打包的js,當然這不是我們想要的。

上面的配置最終可以在dist下打包出下面的文件結構

|-- dist|-- index.js|-- about.js|-- index.html //內掛載index.js|-- about.html //內掛載about.js

通過上面這樣的配置,再加上devServer,我們已經可以實現多頁面的配置開發了,但這樣很不智能,因為你每增加一個頁面,就要在wepback里面配置一次,會非常繁瑣,所以我們來優化下,讓我們只專注于開發頁面,配置交給webpack自己.

webpack多頁面配置優化

我們再看下src下面的文件結構

|-- src|-- index|-- app.js|-- index.scss|-- index.js|-- about|-- app.js|-- index.scss|-- index.js

src下面每個文件夾對應一個html頁面的js業務,如果我們直接把文件夾對應入口js找到并把他們合并生成對應的entry,那是不是就不用手動寫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(); //判斷是不是一個文件夾if(isDirector && item !== "component"){ // component目錄下為組件 需要排除fileArr.push(item);}});return fileArr;} };

比如在src下有index頁面項目,about項目 遍歷結果為["index","about"];

遍歷生成打包入口數組

/* eslint-env node */ /*** @file: getEntry.js 獲取entry文件入口* @author: leinov* @date: 2018-10-11* @update: 2018-11-04 優化入口方法 調用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打包到對應的文件夾下*/entry[`${item}/${item}`] = `${path}/${item}/index.js`;});return entry; };

這里我們使用getFilepath獲取的數組,在獲取到每個目錄下的js文件,組合成一個js入口文件的如下格式的對象。

{"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, })

這樣我們就自動獲取到了entry

html-webpack-plugin自動配置

因為每個頁面都需要配置一個html,而且每個頁面的標題,關鍵字,描述等信息可能不同,所以我們在每個頁面文件夾下創建一個pageinfo.json,通過fs模塊獲取到json里信息再遍歷到對應得html-webpack-plugin中生成一個html插件數組。

index/pageinfo.json 生成index.html頁面信息

{"title":"首頁","keywords":"webpack多頁面" }

about/pageinfo.json 生成about.html頁面信息供

{"title":"關于頁面","keywords":"webpack多頁面關于頁面" }

通過fs遍歷讀取并生成HtmlWebpackPlugin數組供webpack使用

遍歷html插件數組

/*** @file htmlconfig.js 頁面html配置* @author:leinov* @date: 2018-10-09* @update: 2018-11-05* @use: 動態配置html頁面,獲取src下每個文件下的pageinfo.json內容,解析到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文件內容,如果在頁面目錄下沒有找到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多頁面架構",meta:{keywords: infoData.keywords ? infoData.keywords : "webpack,react,github",description:infoData.description ? infoData.description : "這是一個webpack,react多頁面架構"},chunks:[`${item}/${item}`], //引入的jstemplate: "./src/template.html",filename : item == "index" ? "index.html" : `${item}/index.html`, //html位置minify:{//壓縮htmlcollapseWhitespace: 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: entryoutput: {path: path.resolve(__dirname, 'dist'),filename: '[name].js'}....//其他配置devServer: {port: 3100,open: true,},plugins: [...htmlArr] })

這樣一個自動化完整的多頁面架構配置就完成了,如果我們要新創建一個頁面

  • 在src下創建一個文件目錄
  • 在新創建的文件目錄下添加index.js(必須,因為是webpack打包入口文件)
  • 在新創建文件夾下添加pageinfo.json(非必須) 供html插件使用
  • npm run dev開發

完整代碼參考項目code

版本

版本日期分支備注
2.02018-11-08master優化html插件自動化
1.02018-10-07version1.0第一版

總結

以上是生活随笔為你收集整理的webpack+react多页面开发架构的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。