摘要:?jiǎn)栴}來(lái)源于思路使用來(lái)給文件加使用插件來(lái)給文件加使用插件來(lái)自動(dòng)根據(jù)加的來(lái)引入對(duì)應(yīng)的和并生成文件安裝無(wú)需安裝因?yàn)橐呀?jīng)帶了版,如果自己安裝了版反而可能出問(wèn)題。
問(wèn)題來(lái)源于:https://github.com/sorrycc/ro...
Workaround:
使用 webpack output 來(lái)給 js 文件加 hash
使用插件 extract-text-webpack-plugin 來(lái)給 css 文件加 hash
使用插件 html-webpack-plugin 來(lái)自動(dòng)根據(jù)
webpack 加的 hash 來(lái)引入對(duì)應(yīng)的 css 和 js 并生成 html 文件
npm i -D ejs-loader html-webpack-plugin webpack-md5-hash
無(wú)需安裝 extract-text-webpack-plugin 因?yàn)?roadhog 已經(jīng)帶了 1.0.1 版,如果自己安裝了 2.x 版反而可能出問(wèn)題。需要額外安裝 ejs-loader 因?yàn)?webpack 配置里會(huì)用到
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 默認(rèn)配置把非 特定格式 的文件都用 url-loader 去加載,但是 html-webpack-plugin 需要的 ejs 文件會(huì)變成 base64 編碼,所以要把 ejs 格式加入 loader 白名單,參考
[2] 覆蓋 roadhog 的 配置
[3] roadhog 對(duì) html 默認(rèn)用的 file-loader,這里的 html-webpack-plugin 需要讀取其內(nèi)容作為模板,所以換成 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 `` }) %> <% } %>