Skip to content

Commit

Permalink
add boolean and object support
Browse files Browse the repository at this point in the history
  • Loading branch information
duanyuwen committed Jun 9, 2018
1 parent 8c0b347 commit 0426c79
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,22 @@ add custom attributes to inject tags

### use

please use it after `html-webpack-plugin`, especially in webpack2+.

add to all inject tags
```javascript
plugins = [
new htmlWebpackInjectAttributesPlugin({
inject: "true"
inject: "true",
async: true,
test: {}
}) // Object, key should be string, value can be string or function
]
```
you got

```html
<script type="text/javascript" src="index.js" inject="true"></script>
<script type="text/javascript" src="index.js" inject="true" async test="{}"></script>
```

add to chunks in HtmlWebpackPlugin
Expand Down
21 changes: 15 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,15 @@ function addAttr(compilation, tags, key, val) {
var value = val;
if (typeof val === "function") {
value = val(tag, compilation, index);
} else if (typeof val === 'object') {
value = JSON.stringify(val);
}
tag.attributes[key] = value;
});
}
function alterAssetTags(compilation, htmlPluginData, callback) {
var options = assign({}, this.options, htmlPluginData.plugin.options && htmlPluginData.plugin.options.attributes);
forEach(options, function (val, key) {
if (typeof val !== 'string' && typeof val !== 'function') {
return;
}
addAttr(compilation, htmlPluginData.head, key, val);
addAttr(compilation, htmlPluginData.body, key, val);
});
Expand All @@ -37,9 +36,19 @@ function htmlWebpackInjectAttributesPlugin(options) {

htmlWebpackInjectAttributesPlugin.prototype.apply = function (compiler) {
var self = this;
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-alter-asset-tags', alterAssetTags.bind(self, compilation));
});

if (compiler.hooks) {
compiler.hooks.compilation.tap("htmlWebpackInjectAttributesPlugin", function (compilation) {
compilation
.hooks
.htmlWebpackPluginAlterAssetTags
.tap("htmlWebpackInjectAttributesPlugin", alterAssetTags.bind(self, compilation));
});
} else {
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-alter-asset-tags', alterAssetTags.bind(self, compilation));
});
}
};

module.exports = htmlWebpackInjectAttributesPlugin;

0 comments on commit 0426c79

Please sign in to comment.