如何在现代Angular的index.html中配置可切换的Google Analytics ID
现代Angular中配置Google Analytics/GTM多环境变量方案
一、创建环境变量文件
在项目根目录创建以下文件(变量需以NG_APP_开头,Angular才会自动识别):
.env(开发环境)
NG_APP_GA_ID=你的开发GA_ID NG_APP_GTM_ID=你的开发GTM_ID
.env.staging(预发布环境)
NG_APP_GA_ID=你的预发布GA_ID NG_APP_GTM_ID=你的预发布GTM_ID
.env.production(生产环境)
NG_APP_GA_ID=你的生产GA_ID NG_APP_GTM_ID=你的生产GTM_ID
将这些.env文件添加到.gitignore中,避免敏感信息提交到版本库:
.env .env.staging .env.production
二、更新环境配置文件
在src/environments/目录下的环境文件中关联env变量:
environment.ts(开发环境)
export const environment = { production: false, gaId: import.meta.env.NG_APP_GA_ID, gtmId: import.meta.env.NG_APP_GTM_ID };
environment.prod.ts(生产环境)
export const environment = { production: true, gaId: import.meta.env.NG_APP_GA_ID, gtmId: import.meta.env.NG_APP_GTM_ID };
如果需要单独的预发布环境配置,可创建environment.staging.ts:
export const environment = { production: false, gaId: import.meta.env.NG_APP_GA_ID, gtmId: import.meta.env.NG_APP_GTM_ID };
三、修改index.html中的脚本
将固定ID替换为Angular构建时会自动替换的env变量占位符:
<script> window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', '%NG_APP_GA_ID%'); </script> <!-- Google Tag Manager --> <script> (function (w, d, s, l, i) { w[l] = w[l] || []; w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' }); var f = d.getElementsByTagName(s)[0], j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f); })(window, document, 'script', 'dataLayer', '%NG_APP_GTM_ID%'); </script>
四、配置构建命令
编辑angular.json,在architect/build/configurations中添加预发布环境配置:
"configurations": { "production": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ], "envFile": ".env.production" }, "staging": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.staging.ts" } ], "envFile": ".env.staging" } }
同时在architect/serve/configurations中添加预发布环境的启动配置:
"staging": { "browserTarget": "你的项目名称:build:staging" }
五、运行/构建命令
- 开发环境:
ng serve - 预发布环境启动:
ng serve --configuration staging - 预发布环境构建:
ng build --configuration staging - 生产环境构建:
ng build --configuration production
内容的提问来源于stack exchange,提问作者Tuma
相关产品推荐
相关产品推荐

