Created
June 17, 2022 21:10
-
-
Save mishani0x0ef/b15a969c016fa01b85f413b712c40fa1 to your computer and use it in GitHub Desktop.
HtmlTagAttributesPlugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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