Skip to content

Instantly share code, notes, and snippets.

@futurist
Created May 28, 2016 07:41
Show Gist options
  • Save futurist/d14e717baf2fa27b2b0fb070e6a74ad4 to your computer and use it in GitHub Desktop.
Save futurist/d14e717baf2fa27b2b0fb070e6a74ad4 to your computer and use it in GitHub Desktop.
Webpack: Generate [hash].js in production html file
// Webpack: Generate [hash].js in production html file
// From: https://github.com/webpack/webpack/issues/86
if (process.env.NODE_ENV === 'production') {
// Hashing of this kind happens only in prod.
config.output.filename = "bundle-[hash].js"; // In dev's config, it's "bundle.js"
config.plugins.push(
// To rewrite stuff like `bundle.js` to `bundle-[hash].js` in files that refer to it, I tried and
// didn't like the following plugin: https://github.com/ampedandwired/html-webpack-plugin
// for 2 reasons:
// 1. because it didn't work with HMR dev mode...
// 2. because it's centered around HTML files but I also change other files...
// I hope we can soon find something standard instead of the following hand-coding.
function () {
this.plugin("done", function (stats) {
//var stats = statsData.toJson();
var replaceInFile = function (filePath, toReplace, replacement) {
var replacer = function (match) {
console.log('Replacing in %s: %s => %s', filePath, match, replacement);
return replacement
};
var str = fs.readFileSync(filePath, 'utf8');
var out = str.replace(new RegExp(toReplace, 'g'), replacer);
fs.writeFileSync(filePath, out);
};
var hash = stats.hash; // Build's hash, found in `stats` since build lifecycle is done.
replaceInFile(path.join(config.output.path, 'index.html'),
'bundle.js',
'bundle-' + hash + '.js'
);
});
}
);
}
// Another solution:
var Path = require("path");
var FileSystem = require("fs");
var webpackConfig = {
...
plugins: [
...
function() {
this.plugin("done", function(statsData) {
var stats = statsData.toJson();
if (!stats.errors.length) {
var htmlFileName = "index.html";
var html = FileSystem.readFileSync(Path.join(__dirname, htmlFileName), "utf8");
var htmlOutput = html.replace(
/<script\s+src=(["'])(.+?)bundle\.js\1/i,
"<script src=$1$2" + stats.assetsByChunkName.main[0] + "$1");
FileSystem.writeFileSync(
Path.join(__dirname, "%your build path%", htmlFileName),
htmlOutput);
}
});
}
]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment