1.0.1 • Published 5 years ago
webpack-gtag-plugin v1.0.1
#webpack-gtag-plugin
Tracking SPA application with Google Tag Manager (a replacement for GoogleAnalytics, gtag).
How to use?
Caution: This plugin required and you need placed it after of HTMLWebpackPlugin
.
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WebpackGtagPlugin = require('webpack-gtag-plugin');
module.exports = {
// ... other settings
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html',
inject: 'body'
}));
new WebpackGtagPlugin({ id: 'GA_TRACKING_ID' })
]
}
Result look like:
</head>
<!-- other header tags here-->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_TRACKING_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'GA_TRACKING_ID');
/**
* Extra scripts bellow for SPA!
* It may affect outer javascript and framework(like vue, angular, react etc...).
* You should be careful before using it officially
*/
function insertCallback(parent, funcname, callback, ...args) {
let oldFunc = parent[funcname] ? parent[funcname] : function () { }
parent[funcname] = function () {
oldFunc.apply(this, arguments)
return callback(...args)
}
}
function notify_analytics(l) {
let nextPage = l.pathname + l.hash
gtag('config', 'GA_TRACKING_ID', { 'page_path': nextPage });
}
insertCallback(window.history, "pushState", notify_analytics, location)
insertCallback(window.history, "replaceState", notify_analytics, location)
</script>
</head>
Options:
- id: Google Analytics tracking ID.