Skip to content

Instantly share code, notes, and snippets.

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 mrdevin/e8e269cb4a03457be2feea08acf41a3b to your computer and use it in GitHub Desktop.
Save mrdevin/e8e269cb4a03457be2feea08acf41a3b to your computer and use it in GitHub Desktop.
const CODE = `<!-- Global site tag (gtag.js) - Google Analytics -->
<script defer src="https://www.googletagmanager.com/gtag/js?id={{ID}}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '{{ID}}');
</script>`;
class GoogleTagmanagerPlugin {
constructor (id) {
this.id = id;
}
apply (compiler) {
compiler.hooks.compilation.tap('gtag', compilation => {
compilation.hooks.htmlWebpackPluginAfterHtmlProcessing.tap('gtag', ({ html }) => ({
html: html.replace('</body>', CODE.replace(new RegExp('{{ID}}', 'g'), this.id) + '</body>')
}));
});
}
}
module.exports = GoogleTagmanagerPlugin
{
"name": "google-tagmanager-webpack-plugin",
"version": "0.1.0",
"main": "google-tagmanager-webpack-plugin.js"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment