Webpack Plugin 自動生成版本號等配置並通過前端伺服器獲取更新微信快取舊程式碼問題

MiWi銳霸發表於2018-12-28

[目錄]
背景
引申問題
思路
使用示例

  • Env新增版本變數
  • 外掛程式碼
  • 配置檔案中引入VersionPlugin
  • 驗證版本號並處理
  • Shell終端執行打包

優化

  • 如何通過編譯指令指定版本號?
  • 其他外掛

其他處理快取方式及問題
參考文章

[TAG]:

  • Vue
  • JavaScript
  • Webpack Plugin
  • 自動版本號
  • 微信快取更新

背景

微信H5開發中,遇到了問題:

  • 微信H5對Index.html快取問題,使得提測過程中、釋出Release版本後,使用者端看到的頁面依舊是快取的html/js/cs
  • 在JavaScrip檔案分包情況下,專案重新打包後,由於釋出時清除了原js檔案,如果html已快取,就會出現載入不到js的錯誤
  • 由於需求和測試需要,支付渠道需要切換,每次為了一個配置引數卻需要反覆提交TAG

引申問題

  • 版本號如何自動生成?能否指定版本號?
  • 如何獲取版本號等配置?通過Service伺服器API獲取就會對Service侵入——介面同學要是善良尚可,要是......

思路

本著自己的問題自己解決,既然前端都是伺服器在跑,那就直接提供個配置訪問檔案,打包時複製一份豈不快哉。但是每次提測、釋出都還得手動修改版本?怎麼行?通過Webpack Plugin、執行指令碼自動生成吧。

前提: js等檔案需要通過hash配置檔名,否則在微信快取過期前貌似只能通過手動清理快取處理。檔名配置參考

使用示例

Env新增版本變數

// 示例 
// 檔案:/config/prod.env.js
module.exports = {
  NODE_ENV: '"production"',
  VERSION:'"v1.0 [' + new Date().toLocaleString() + ']"'
}
// 檔案:/config/dev.env.js
module.exports = merge(prodEnv, { // 這裡使用了merge, 為了後續判斷所以需要設定空字串
  NODE_ENV: '"development"',
  VERSION: '""', // 開發環境置空才不會判斷版本,因為開發環境未配置自動生成版本配置資訊
}
// 檔案:/config/index.js
module.exports = {
  dev: { ... },
  build: { env: require('./prod.env') }
}
複製程式碼

外掛程式碼

'use strict';

var FStream = require('fs');

/**
 * 版本資訊生成外掛
 * @author phpdragon@qq.com
 * @param options
 * @constructor
 */
function VersionPlugin(options) {
  this.options = options || {};
  !this.options.versionDirectory && (this.options.versionDirectory = 'static');
}

// apply方法是必須要有的,因為當我們使用一個外掛時(new somePlugins({})),webpack會去尋找外掛的apply方法並執行
VersionPlugin.prototype.apply = function (compiler) {
  var self = this;
  compiler.plugin("compile", function (params) {
    var dir_path = this.options.context + '/' + self.options.versionDirectory;
    var version_file = dir_path + '/version.json';
    var content = '{"version":' + self.options.env.VERSION + '}';
    FStream.exists(dir_path, function (exist) {
      if (exist) {
        writeVersion(self, version_file, content);
        return;
      }
      FStream.mkdir(dir_path, function (err) {
        if (err) throw err;
        console.log('\n建立目錄[' + dir_path + ']成功');
        writeVersion(self, version_file, content);
      });
    });
  });
  //編譯器'對'所有任務已經完成'這個事件的監聽
  compiler.plugin("done", function (stats) {
    console.log("應用編譯完成!");
  });
};

const writeVersion = (self, versionFile, content) => {
  console.log("\n當前版本號:" + self.options.env.VERSION);
  console.log("開始寫入版本資訊...");
  //寫入檔案
  FStream.writeFile(versionFile, content, function (err) {
    if (err) throw err;
    console.log("版本資訊寫入成功!");
  });
}

module.exports = VersionPlugin;
複製程式碼

配置檔案中引入VersionPlugin

// 檔案:/build/webpack.prod.conf.js
const config = require('../config');
const VersionPlugin = require('./version-plugin');
const webpackConfig = merge(baseWebpackConfig, {
  plugins: [
    new VersionPlugin({ path: config.build.assetsRoot, env: config.build.env, versionDirectory: 'static'}),
  ]
}
複製程式碼

驗證版本號並處理

// 專案配置的入口檔案,如檔案:./src/main.js
import Vue from 'vue';
import router from './router';
import axios from 'axios';
import { ToastPlugin } from 'vux';
/** 
  * 〖Author〗 MiWi.LIN ^^^^〖E-mail〗 80383585@qq.com
  *  Copyright(c) 2018/12/28
  * 〖Version〗 1.0
  * 〖Date〗 2018/12/28_上午10:45
  */ 
const { VERSION } = process.env;

Vue.use(ToastPlugin);

function ifVersionCorrect(to, from, next) {
    ...
    next(); // 不適合呼叫引數, 如next('/')會出現死迴圈,原因在於引數情況下會第二次執行router.beforeEach的回撥函式
}

function checkVersion(to, from, next) {
  console.info('當前版本:', VERSION);
  axios.get(`../static/version.json?_=${Math.random()}`).then((response) => { // 訪問前端伺服器獲取版本號
    if (response.status === 200 && VERSION !== response.data.version) {
      Vue.$vux.toast.text('發現新版本,自動更新中...');
      console.info('新版本:', response.data.version);
      setTimeout(() => {
        location.reload(true);
      }, 500);
      return;
    }
    ifVersionCorrect(to, from, next);
  }).catch((err) => {
    console.error('checkVersion', err);
    ifVersionCorrect(to, from, next);
  });
}

router.beforeEach((to, from, next) => {
  // 未匹配路由跳轉到首頁
  if (!to.name) {
    next({ name: 'index' });
    return;
  }
  if (VERSION && to.name === 'index') { // VERSION在prod.env中配置,作為區分生產環境
    checkVersion(to, from, next);
  } else {
    ifVersionCorrect(to, from, next);
  }
});
複製程式碼
  • 這裡只對進入Index時校驗版本,所以相關邏輯也可以在首頁Index.vue中做處理

Shell終端執行打包

> npm run build
當前版本號:"v1.0 [2018-12-28 10:00:41]"
開始寫入版本資訊...
版本資訊寫入成功!
複製程式碼

優化

如何通過編譯指令指定版本號?

// 檔案:/config/prod.env.js
module.exports = {
  NODE_ENV: '"production"',
  VERSION: JSON.stringify(process.env.VERSION_ENV) || '"v1.0 [' + new Date().toLocaleString() + ']"'
}
// 檔案: /package.json
{
  "scripts": {
  "build:2": "cross-env VERSION_ENV=v2.0 webpack --config build/build.js"
  }
}
複製程式碼

Shell終端執行打包

> npm run build:2
複製程式碼

說明

  • 如不配置build:2,可在終端中直接輸入指令內容, 實時動態設定版本,嫌指令太長?去看看Shell終端的alais配置...
  • 這樣就可以通過process.env.VERSION_ENV獲取到值v2.0
  • 關於cross-env可以參考使用cross-env解決跨平臺設定NODE_ENV的問題,主要是解決不同系統環境指令相容問題
  • 如不使用cross-env,可通過process.argv獲取指令引數,方式參考:
for (var i in process.argv) {
  if (process.argv[i] === "--production") { ... }
}
// 或 process.argv.includes('--production')
複製程式碼

其他外掛

使用webpack進行版本管理工具(webpack-plugin-auto-version)_GitHub
versiony-自動修改package.json中專案版本號

其他處理快取方式及問題

方式一:

修改伺服器nginx no-cache配置,需要運營配置(沒試過...)

方式二:

Index.html中配置no-cache:

<html manifest="IGNORE.manifest">  <!--靜態html檔案遇到微信快取而無法及時更新,html標籤中增加不存在的manifest檔案連結-->
<!--no-cache相關-->
<!--no-cache瀏覽器會快取,但重新整理頁面或者重新開啟時 會請求伺服器,伺服器可以響應304,如果檔案有改動就會響應200-->
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
複製程式碼

存在問題: - IGNORE.manifest 會引起500錯誤,使用時存在個別機型、微信版本無效,仍使用快取檔案,還得手動重新整理 - 不能解決上文提到的分包問題

方式三:

Cache Buster方式: route url新增版本號或隨機數

如:/index.html?v=1#/list

存在問題: - 在專案業務中,跳轉微信或其他第三方頁面後,原邏輯可能會使引數失效,返回原快取頁面,載入微信中已快取的舊邏輯 - 還是不能解決上文提到的分包問題 - 微信公眾號使用場景中,每次版本釋出得在微信後臺修改URL - Vue中同一頁面route跳轉不會重新整理快取,參考vue-router原始碼分析-整體流程

方式四:

上文提到的,需要介面同學配合。
系統內部通過ajax請求獲取版本資訊從而提示更新。
存在問題:對後端系統有侵入性,屬於下策。

參考文章

webpack + vue 專案 自定義 外掛 解決 前端 JS 版本 更新 問題
Webpack外掛開發簡要
webpack 打包傳參 process.env 公司一個專案多個版本的前端架構方案
webpack使用和踩過的坑

相關文章