roadhog 生產環境支持靜態文件名加 hash 和 CDN 配置

問題來源於:https://github.com/sorrycc/ro...css

Workaround:html

思路

安裝

npm i -D ejs-loader html-webpack-plugin webpack-md5-hash

無需安裝 extract-text-webpack-plugin 由於 roadhog 已經帶了 1.0.1 版,若是本身安裝了 2.x 版反而可能出問題。須要額外安裝 ejs-loader 由於 webpack 配置裏會用到web

webpack.config.js

const ExtractTextPlugin = require('extract-text-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const WebpackMd5Hash = require('webpack-md5-hash')

module.exports = function (config, env) {
  config.module.loaders[0].exclude.push(/\.ejs$/)    // 注 1
  if (env === 'production') {
    config.output.filename = '[name].[chunkhash].js'
    config.output.chunkFilename = '[chunkhash].async.js'
    config.plugins[3] = new ExtractTextPlugin('[contenthash:20].css')    // 注 2
    config.plugins.push(
      new HtmlWebpackPlugin({
        template: 'ejs!src/index.ejs',    // 注 3
        inject: false,
        minify: { collapseWhitespace: true },
        production: true,
      }),
      new WebpackMd5Hash()
    )
  } else {
    config.plugins.push(
      new HtmlWebpackPlugin({
        template: 'ejs!src/index.ejs',
        inject: true,
      }),
    )
  }
  return config
}

[1] roadhog 默認配置把非 特定格式 的文件都用 url-loader 去加載,可是 html-webpack-plugin 須要的 ejs 文件會變成 base64 編碼,因此要把 ejs 格式加入 loader 白名單,參考 npm

[2] 覆蓋 roadhog 的 配置json

[3] roadhog 對 html 默認用的 file-loader,這裏的 html-webpack-plugin 須要讀取其內容做爲模板,因此換成 ejs,也就再也不須要 index.html緩存

.roadhogrc

{
  "env": {
    "production": {
      "define": {
        "__CDN__": "https://cdn.example.com"
      }
    }
  }
}

.eslintrc

{
  "globals" : {
    "__CDN__": false
  }
}

index.ejs

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <% if (htmlWebpackPlugin.options.production) { %>
    <%= htmlWebpackPlugin.files.css.map((item) => {
      return `<link href="${__CDN__}${item}" rel="stylesheet">`
    }) %>
  <% } %>
</head>
</head>
<body>
  <div id="root"></div>
  <% if (htmlWebpackPlugin.options.production) { %>
    <%= htmlWebpackPlugin.files.js.map((item) => {
      return `<script src="${__CDN__}${item}" charset="utf-8"></script>`
    }) %>
  <% } %>
</body>
</html>

index.js 裏去掉 `import './index.html' (若是有的話)async

這樣就同時兼顧了開發環境和部署環境使用同一套 html 入口,而且開發環境使用本地文件,部署環境使用按照文件內容 MD5 命名了的 CDN 文件(方便緩存控制)

參考

相關文章
相關標籤/搜索