Skip to content

Instantly share code, notes, and snippets.

@mishani0x0ef
Created June 17, 2022 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mishani0x0ef/b15a969c016fa01b85f413b712c40fa1 to your computer and use it in GitHub Desktop.
Save mishani0x0ef/b15a969c016fa01b85f413b712c40fa1 to your computer and use it in GitHub Desktop.
HtmlTagAttributesPlugin
const HtmlWebpackPlugin = require('html-webpack-plugin');
// For more information about plugin concepts, see: https://github.com/jantimon/html-webpack-plugin#events
class HtmlTagAttributesPlugin {
static name = 'HtmlTagAttributesPlugin';
constructor(options) {
const defaultOptions = {
script: {},
};
this.options = { ...defaultOptions, ...options };
}
apply(compiler) {
compiler.hooks.compilation.tap(
HtmlTagAttributesPlugin.name,
(compilation) => this._hookIntoHtmlAlterAssetTags(compilation)
);
}
_hookIntoHtmlAlterAssetTags(compilation) {
HtmlWebpackPlugin.getHooks(compilation).alterAssetTags.tapAsync(
HtmlTagAttributesPlugin.name,
(data, cb) => cb(null, this._extendScriptTags(data))
);
}
_extendScriptTags(data) {
data.assetTags.scripts = data.assetTags.scripts.map(
({ attributes, ...other }) => ({
...other,
attributes: {
...attributes,
...this.options.script,
},
})
);
return data;
}
}
module.exports = { HtmlTagAttributesPlugin };
module.exports = {
// some configs
plugins: [
new HtmlWebpackPlugin({
// your config here
}),
// example of adding onerror attribute to all script tags
new HtmlTagAttributesPlugin({
script: {
// timeout used in order to avoid frequent reloads in case of total disaster
onerror: `(function() {
setTimeout(function() {
window.location.reload();
}, 3000);
})()`,
},
}),
]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment