From ae8233a04d4105b6e970feaa2c5e11c0b48fd4b7 Mon Sep 17 00:00:00 2001 From: Jan Nicklas Date: Tue, 7 Aug 2018 15:15:29 +0200 Subject: [PATCH] feat: Add support for the [contenthash] placeholder inside htm file names --- index.js | 13 ++++++++++--- spec/basic.spec.js | 20 ++++++++++++++++++-- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index 193fbc9a..d9060862 100644 --- a/index.js +++ b/index.js @@ -14,6 +14,7 @@ const vm = require('vm'); const fs = require('fs'); const _ = require('lodash'); const path = require('path'); +const loaderUtils = require('loader-utils'); const htmlTagObjectToString = require('./lib/html-tags').htmlTagObjectToString; @@ -238,15 +239,21 @@ class HtmlWebpackPlugin { return self.options.showErrors ? prettyError(err, compiler.context).toHtml() : 'ERROR'; }) .then(html => { + // Allow to use [contenthash] as placeholder for the html-webpack-plugin name + // From https://github.com/webpack-contrib/extract-text-webpack-plugin/blob/8de6558e33487e7606e7cd7cb2adc2cccafef272/src/index.js#L212-L214 + const finalOutputName = self.childCompilationOutputName.replace(/\[(?:(\w+):)?contenthash(?::([a-z]+\d*))?(?::(\d+))?\]/ig, function () { + return loaderUtils.getHashDigest(html, arguments[1], arguments[2], parseInt(arguments[3], 10)); + }); // Replace the compilation result with the evaluated html code - compilation.assets[self.childCompilationOutputName] = { + compilation.assets[finalOutputName] = { source: () => html, size: () => html.length }; + return finalOutputName; }) - .then(() => getHtmlWebpackPluginHooks(compilation).afterEmit.promise({ + .then((finalOutputName) => getHtmlWebpackPluginHooks(compilation).afterEmit.promise({ html: compilation.assets[self.childCompilationOutputName], - outputName: self.childCompilationOutputName, + outputName: finalOutputName, plugin: self }).catch(err => { console.error(err); diff --git a/spec/basic.spec.js b/spec/basic.spec.js index fd2f49d8..8b4f5c49 100644 --- a/spec/basic.spec.js +++ b/spec/basic.spec.js @@ -50,8 +50,9 @@ function testHtmlPlugin (webpackConfig, expectedResults, outputFile, done, expec expect(compilationWarnings).toBe(''); } if (outputFile instanceof RegExp) { + const fileNames = Object.keys(stats.compilation.assets); const matches = Object.keys(stats.compilation.assets).filter(item => outputFile.test(item)); - expect(matches.length).toBe(1); + expect(matches[0] || fileNames).not.toEqual(fileNames); outputFile = matches[0]; } expect(outputFile.indexOf('[hash]') === -1).toBe(true); @@ -629,6 +630,22 @@ describe('HtmlWebpackPlugin', () => { }, ['