An Rsbuild plugin to setup Google Analytics in your website.
Install:
npm add rsbuild-plugin-google-analytics -DAdd plugin to your rsbuild.config.ts:
// rsbuild.config.ts
import { pluginGoogleAnalytics } from 'rsbuild-plugin-google-analytics';
export default {
plugins: [
pluginGoogleAnalytics({
// replace this with your Google tag ID
// see: https://support.google.com/analytics/answer/9539598?hl=en
id: 'G-xxxxxxxxxx',
}),
],
};Here are the available options:
| Name | Type | Description | Defaults |
|---|---|---|---|
| id | string |
Google tag ID | undefined |
| enable | boolean |
Whether to enable Google Analytics | true |
| scriptLoading | 'async' | 'defer' |
Loading strategy for the external Google tag script | 'async' |
The default async matches Google's setup example and executes the external script as soon as it is available.
Set scriptLoading to defer to execute the external script after HTML parsing, in document order with other deferred scripts:
pluginGoogleAnalytics({
id: 'G-xxxxxxxxxx',
scriptLoading: 'defer',
});This option only affects the external script. The inline dataLayer and gtag initialization still runs immediately so events can be queued before the external script loads.
A deferred script delays DOMContentLoaded and can delay other deferred scripts placed after it. It does not guarantee execution after application hydration.
If you experience this error on UI side window.gtag is not a function, you may need to add types for gtag by installing this package:
npm install --save-dev @types/gtag.jsand you also have to add it to the types in your tsconfig.json:
{
"compilerOptions": {
"types": ["gtag.js"]
}
}Then you won't experience any TS errors with code like this:
if (isProd()) {
gtag('event', 'exception', { description: err.message });
}MIT.