-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
54 lines (54 loc) · 1.91 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AssetAttributesPlugin = void 0;
const html_webpack_plugin_1 = __importDefault(require("html-webpack-plugin"));
// replace lodash `_.escape()`
function escapeHTML(t) {
if (!t) {
return '';
}
const escapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
};
return t.replace(/[&<>"']/g, (c) => escapes[c]);
}
class AssetAttributesPlugin {
constructor({ scriptAttribs = {}, styleAttribs = {} }) {
this.scriptAttribs = scriptAttribs;
this.styleAttribs = styleAttribs;
}
apply(compiler) {
compiler.hooks.compilation.tap(this.constructor.name, (compilation) => {
html_webpack_plugin_1.default.getHooks(compilation).alterAssetTags.tapAsync(this.constructor.name, (data, cb) => {
function e(v) {
if (typeof v === 'boolean') {
return v;
}
return escapeHTML(v);
}
const scriptAttribs = Object.entries(this.scriptAttribs).map(([k, v]) => ({
[k]: e(v),
}));
const styleAttribs = Object.entries(this.styleAttribs).map(([k, v]) => ({
[k]: e(v),
}));
const { scripts, styles } = data.assetTags;
scripts.forEach((s) => {
Object.assign(s.attributes, ...scriptAttribs);
});
styles.forEach((s) => {
Object.assign(s.attributes, ...styleAttribs);
});
cb(null, data);
});
});
}
}
exports.AssetAttributesPlugin = AssetAttributesPlugin;