sco*_*vic 2 google-analytics angular
我有一些 Angular 项目之外的 Google Analytics 代码。如果环境是生产环境,我只想包括它。
我知道有一个环境变量中的角项目,你可以像这里面的打字稿参考...
if (environment.production) {
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
如果在 Angular 之外有一些静态代码,那也无济于事。我尝试将 Google 分析代码放在 Angular 中,但这似乎存在未找到范围的问题,并且打字稿不喜欢它。
现在我最好的解决方案是手动检查主机名,这可能不是最好的解决方案(这是在 angular 应用程序之外的 index.html 中)...
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-00000000-0"></script>
<script>
if(location.hostname === "productionurl.com") {
// insert google analytics tracking code
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-000000000-0');
}
</script>
Run Code Online (Sandbox Code Playgroud)
我习惯使用 web.config 文件,这很简单,但这个项目使用 angular 配置来处理环境变量。
也许有一种方法可以从 vanilla javascript 中的“getAllAngularRootElements()”之类的东西获取环境,但我还没有找到方法。
对我来说,目前最干净的解决方案是使用第二个index.html文件,例如index.prod.html,并在构建过程中使用.env 配置中的"fileReplacements"属性替换原始文件。"production"angular.json
在这里查看:https : //github.com/angular/angular-cli/wiki/stories-application-environments
UDPATE 用于 Angular 8+
在构建时,"fileReplacements"将无法替换index.html- 使用"index":
"index": {
"input": "src/index.prod.html",
"output": "index.html"
},
Run Code Online (Sandbox Code Playgroud)
更多信息在这里:https : //github.com/angular/angular-cli/issues/14599
| 归档时间: |
|
| 查看次数: |
1265 次 |
| 最近记录: |