-
-
Notifications
You must be signed in to change notification settings - Fork 9.9k
Expand file tree
/
Copy pathindex.ts
More file actions
89 lines (78 loc) · 2.43 KB
/
index.ts
File metadata and controls
89 lines (78 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type {LoadContext, Plugin} from '@docusaurus/types';
import type {PluginOptions, Options} from './options';
function createConfigSnippet(trackingID: string): string {
return `gtag('config', '${trackingID}');`;
}
function createConfigSnippets({
trackingID: trackingIDArray,
}: PluginOptions): string {
return trackingIDArray.map(createConfigSnippet).join('\n');
}
export default function pluginGoogleGtag(
context: LoadContext,
options: PluginOptions,
): Plugin | null {
if (process.env.NODE_ENV !== 'production') {
return null;
}
const firstTrackingId = options.trackingID[0];
return {
name: 'docusaurus-plugin-google-gtag',
contentLoaded({actions}) {
actions.setGlobalData(options);
},
getClientModules() {
return ['./gtag'];
},
injectHtmlTags() {
return {
// Gtag includes GA by default, so we also preconnect to
// google-analytics.
headTags: [
{
tagName: 'link',
attributes: {
rel: 'preconnect',
href: 'https://www.google-analytics.com',
},
},
{
tagName: 'link',
attributes: {
rel: 'preconnect',
href: 'https://www.googletagmanager.com',
},
},
{
tagName: 'script',
attributes: {
async: true,
// We only include the first tracking id here because google says
// we shouldn't install multiple tags/scripts on the same page
// Instead we should load one script and use n * gtag("config",id)
// See https://developers.google.com/tag-platform/gtagjs/install#add-products
src: `https://www.googletagmanager.com/gtag/js?id=${firstTrackingId}`,
},
},
{
tagName: 'script',
innerHTML: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
${createConfigSnippets(options)};
`,
},
],
};
},
};
}
export {validateThemeConfig, validateOptions} from './options';
export type {PluginOptions, Options};