Skip to content

Commit 0426c79

Browse files
author
duanyuwen
committed
add boolean and object support
1 parent 8c0b347 commit 0426c79

File tree

2 files changed

+21
-8
lines changed

2 files changed

+21
-8
lines changed

README.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,22 @@ add custom attributes to inject tags
88

99
### use
1010

11+
please use it after `html-webpack-plugin`, especially in webpack2+.
12+
1113
add to all inject tags
1214
```javascript
1315
plugins = [
1416
new htmlWebpackInjectAttributesPlugin({
15-
inject: "true"
17+
inject: "true",
18+
async: true,
19+
test: {}
1620
}) // Object, key should be string, value can be string or function
1721
]
1822
```
1923
you got
2024

2125
```html
22-
<script type="text/javascript" src="index.js" inject="true"></script>
26+
<script type="text/javascript" src="index.js" inject="true" async test="{}"></script>
2327
```
2428

2529
add to chunks in HtmlWebpackPlugin

index.js

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,15 @@ function addAttr(compilation, tags, key, val) {
1010
var value = val;
1111
if (typeof val === "function") {
1212
value = val(tag, compilation, index);
13+
} else if (typeof val === 'object') {
14+
value = JSON.stringify(val);
1315
}
1416
tag.attributes[key] = value;
1517
});
1618
}
1719
function alterAssetTags(compilation, htmlPluginData, callback) {
1820
var options = assign({}, this.options, htmlPluginData.plugin.options && htmlPluginData.plugin.options.attributes);
1921
forEach(options, function (val, key) {
20-
if (typeof val !== 'string' && typeof val !== 'function') {
21-
return;
22-
}
2322
addAttr(compilation, htmlPluginData.head, key, val);
2423
addAttr(compilation, htmlPluginData.body, key, val);
2524
});
@@ -37,9 +36,19 @@ function htmlWebpackInjectAttributesPlugin(options) {
3736

3837
htmlWebpackInjectAttributesPlugin.prototype.apply = function (compiler) {
3938
var self = this;
40-
compiler.plugin('compilation', function (compilation) {
41-
compilation.plugin('html-webpack-plugin-alter-asset-tags', alterAssetTags.bind(self, compilation));
42-
});
39+
40+
if (compiler.hooks) {
41+
compiler.hooks.compilation.tap("htmlWebpackInjectAttributesPlugin", function (compilation) {
42+
compilation
43+
.hooks
44+
.htmlWebpackPluginAlterAssetTags
45+
.tap("htmlWebpackInjectAttributesPlugin", alterAssetTags.bind(self, compilation));
46+
});
47+
} else {
48+
compiler.plugin('compilation', function (compilation) {
49+
compilation.plugin('html-webpack-plugin-alter-asset-tags', alterAssetTags.bind(self, compilation));
50+
});
51+
}
4352
};
4453

4554
module.exports = htmlWebpackInjectAttributesPlugin;

0 commit comments

Comments
 (0)