使用 Webpack 爲單頁面應用發佈新版本

簡介

如今單頁面網站開發通常會用 npm run build 執行 webpack 打包程序用來壓縮 js css 之類。
某一天,跟同事交流時發現能夠這樣搞:javascript

  • 服務器上跑一個 nodejs 進程,如 http://yoursite.com:8080css

  • 在 Webpack 打包結束時自動 request.get 一下服務器 http://yousite.com:8080/?newhash=xxxhtml

  • 服務器接收到 get 請求後有 nodejs 腳本將單頁面應用的 index.html 中引用的版本號替換成這個新的版本java

實現最簡便高效的發佈新版本node

詳細步驟

服務器環節

用到三個文件:webpack

  • index.html 單頁面應用入口git

  • tpl.html 做爲 index.html 的母版,引用的 js 地址爲 http://__CDN_URL__/site-assets/xxx.__VERSION__.js,其中 __VERSION__ 是版本號的 placeholdergithub

  • index.js 跑 nodejs 服務器和替換版本號程序的腳本web

index.js 代碼示例npm

var startCopyHtml = function(newhash) {
  var tplContent = fs.readFileSync('./tpl.html').toString()
  tplContent = tplContent.replace('__VERSION__', newhash)
  fs.writeFileSync('./index.html', tplContent)
}
require("http").createServer(function(req, res) {
  var parsedUrl = require("url").parse(req.url, true);
  var queryAsObject = parsedUrl.query;
  if(queryAsObject.newhash) {
    startCopyHtml(queryAsObject.newhash)
  }
  res.end('ok');
}).listen(8080);

以上代碼只是示範,不要用於生產環境。

推薦能夠作如下安全措施

  • 本地設置特殊的請求頭,服務器檢查請求頭。如特殊的 user agent

  • 校驗 newhash 參數

  • 檢查傳入的 newhash 對應的 js 和 css 的 cdn 地址是否已生效(cdn 回源有延時)

  • 白名單限制 IP 來源

  • 本地和服務器作一個密文對照表,訪問時帶上密文進行驗證

服務器環節配置能夠參考:webpack-deploy-markdown-site-server

Webpack 配置環節

在 Webpack 中的 output.publicPath 配置爲 CDN 的絕對地址。如:

config.output.publicPath = "http://__CDN_URL__/site-assets/"
config.output.filename = "build.[hash].js"

在 Webpack config.plugins 配置中,添加監聽 done 事件的回調。在回調中執行如下任務:

  1. 同步 Webpack 打包好的靜態資源到 CDN 的腳本

  2. 經過訪問 http://yoursite.com:8080/?new-deploy-hash=xxx 來更新網站的靜態資源引用地址。

config.plugins = [
  function() {
    this.plugin('done', function(stats) {
      require('./upload-qiniu')
      require('./update-assets-version')(stats.hash)
    })
  },
  // 其餘插件 ...
}

./upload-qiniu.js 代碼

var qiniu = require('gulp-qiniu');
var cdnConfig = {
  accessKey: "__QINIU_KEY__",
  secretKey: "__QINIU_SECRET__",
  bucket: "__QINIU_BUCKET__",
  private: false
}

var uploadCdn = function (src, cdnDest) {
  if(!src || !cdnDest)
    return
  cdnConfig.dest = cdnDest
  require('vinyl-fs').src(src)
    .pipe(qiniu(cdnConfig, {
      dir: cdnDest,
      versioning: false,
      concurrent: 10
    }))
}

uploadCdn(/*webpack打包產生的 build 地址*/'./build/**', 'site-assets/')

./update-assets-version.js

module.exports = function(hash) {
  var deployHashUrl = 'http://yoursite.com:8080/?newhash=' + hash
  require('http').get(deployHashUrl);
}

Demo

個人博客(http://zaishanda.com/)就是用這種方法部署的。

這個博客的代碼在此:webpack-deploy-markdown-site

Q&A

安全嗎?

服務器環節,替換 index.html 中的版本以前要檢查傳入的 newhash 對應的 cdn 地址是真實存在的纔去替換。
再在服務器上加上 IP 白名單限制訪問 http://yoursite.com:8080/ 這樣就足夠安全了。

跟 git 發佈有什麼優點啊?

比 git 發佈門檻低不少。這個方案只要服務器上有 nodejs 就能夠處理全部事情了。不用在服務器建 git repo,也不須要配置 hook 操做。

跟運行 ssh 命令把修改後的 index.html 上傳比有何優點?

scp rsync 之類的部署方案得在 Webpack 中運行 ssh 腳本,這要每臺本地機器都有 ssh 權限。還會在每臺本地機器暴露服務器上的地址。

原文連接:http://zaishanda.com/post/3

相關文章
相關標籤/搜索