问题来源于:https://github.com/sorrycc/ro...css
Workaround:html
使用 webpack output 来给 js 文件加 hashwebpack
使用插件 extract-text-webpack-plugin 来给 css 文件加 hashgit
使用插件 html-webpack-plugin 来自动根据
webpack 加的 hash 来引入对应的 css 和 js 并生成 html 文件github
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
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缓存
{ "env": { "production": { "define": { "__CDN__": "https://cdn.example.com" } } } }
{ "globals" : { "__CDN__": false } }
<!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 文件(方便缓存控制)
参考