淺談webpack+react多頁面開發終極架構

這篇文章主要介紹了淺談webpack+react多頁面開發終極架構,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

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

概覽

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

特性

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

安裝&使用

// clone
git clone [email protected]:leinov/webpack-react-multi-page.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.html
        template: "./src/template.html",}) //模板
        chunks:["index"]
      }),
    new HtmlWebpackPlugin(
      {
        filename:"about.html",//生成的index.html
        template: "./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}`], //引入的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
  ]
})

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

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

完整代碼參考項目code

版本

版本 日期 分支 備註
2.0 2018-11-08 master 優化html插件自動化
1.0 2018-10-07 version1.0 第一版

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

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