Skip to content

Commit 7fb3efb

Browse files
authored
Adding HtmlWebpackPlugin@4 support (#23)
1 parent 1cedba7 commit 7fb3efb

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-5
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
},
3232
"peerDependencies": {
3333
"webpack": "^2 || ^3 || ^4",
34-
"html-webpack-plugin": "^2 || ^3"
34+
"html-webpack-plugin": "^2 || ^3 || ^4"
3535
},
3636
"devDependencies": {
3737
"codecov": "^3.1.0",

plugin.js

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,18 @@ const flatten = require('lodash/flatten');
66
const isFunction = require('lodash/isFunction');
77
const get = require('lodash/get');
88

9+
// Attempt to load HtmlWebpackPlugin@4
10+
// Borrowed from https://github.com/waysact/webpack-subresource-integrity/blob/master/index.js
11+
let HtmlWebpackPlugin;
12+
try {
13+
// eslint-disable-next-line global-require
14+
HtmlWebpackPlugin = require('html-webpack-plugin');
15+
} catch (e) {
16+
if (!(e instanceof Error) || e.code !== 'MODULE_NOT_FOUND') {
17+
throw e;
18+
}
19+
}
20+
921
const defaultPolicy = {
1022
'base-uri': "'self'",
1123
'object-src': "'none'",
@@ -188,10 +200,19 @@ class CspHtmlWebpackPlugin {
188200
apply(compiler) {
189201
if (compiler.hooks) {
190202
compiler.hooks.compilation.tap('CspHtmlWebpackPlugin', compilation => {
191-
compilation.hooks.htmlWebpackPluginAfterHtmlProcessing.tapAsync(
192-
'CspHtmlWebpackPlugin',
193-
this.processCsp.bind(this)
194-
);
203+
if (HtmlWebpackPlugin && HtmlWebpackPlugin.getHooks) {
204+
// HTMLWebpackPlugin@4
205+
HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync(
206+
'CspHtmlWebpackPlugin',
207+
this.processCsp.bind(this)
208+
);
209+
} else {
210+
// HTMLWebpackPlugin@3
211+
compilation.hooks.htmlWebpackPluginAfterHtmlProcessing.tapAsync(
212+
'CspHtmlWebpackPlugin',
213+
this.processCsp.bind(this)
214+
);
215+
}
195216
});
196217
} else {
197218
compiler.plugin('compilation', compilation => {

0 commit comments

Comments
 (0)