astro添加谷歌分析

安装partytown

1
2
3

pnpm install @astrojs/partytown

启用partytown,在astro.config.ts文件下添加下列文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

import partytown from '@astrojs/partytown'



export default defineConfig({

integrations: [

partytown({

config: {

forward: ["dataLayer.push"],

},

}),

]

});

header.astro文件添加谷歌分析代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

<!-- Google tag (gtag.js) -->

<script type="text/partytown" async src="https://www.googletagmanager.com/gtag/js?id=G-MZXCQSZ8FT"></script>

<script type="text/partytown">

window.dataLayer = window.dataLayer || [];

function gtag(){dataLayer.push(arguments);}

gtag('js', new Date());



gtag('config', '你的谷歌代码');

</script>

测试是否成功

在谷歌分析中这个页面可以进行测试的