摘要:问题来源于思路使用来给文件加使用插件来给文件加使用插件来自动根据加的来引入对应的和并生成文件安装无需安装因为已经带了版,如果自己安装了版反而可能出问题。
问题来源于:https://github.com/sorrycc/ro...
Workaround:
使用 webpack output 来给 js 文件加 hash
使用插件 extract-text-webpack-plugin 来给 css 文件加 hash
使用插件 html-webpack-plugin 来自动根据
webpack 加的 hash 来引入对应的 css 和 js 并生成 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 配置里会用到
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 白名单,参考
[2] 覆盖 roadhog 的 配置
[3] roadhog 对 html 默认用的 file-loader,这里的 html-webpack-plugin 需要读取其内容作为模板,所以换成 ejs,也就不再需要 index.html
{
"env": {
"production": {
"define": {
"__CDN__": "https://cdn.example.com"
}
}
}
}
{
"globals" : {
"__CDN__": false
}
}
Example <% if (htmlWebpackPlugin.options.production) { %> <%= htmlWebpackPlugin.files.css.map((item) => { return `` }) %> <% } %> <% if (htmlWebpackPlugin.options.production) { %> <%= htmlWebpackPlugin.files.js.map((item) => { return `` }) %> <% } %>