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 文件(方便缓存控制)

参考

相关文章
相关标签/搜索