简体   繁体   English

在 index.html 中使用环境变量

[英]Use environement variable in index.html

I'm using angular and I want to use an environment variable in my index.html for google analytics.我正在使用 angular 并且我想在我的 index.html 中使用环境变量进行谷歌分析。 I tried like this:我试过这样:

<script>
    import {environment} from "./environments/environment";
</script>
<!-- End Google Tag Manager (noscript) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=" + environment.googleAnalytics></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());


    gtag('config', environment.googleAnalytics);
</script>

But not working in the link of script.但不能在脚本的链接中工作。 Can you help me please?你能帮我吗? In this place https://www.googletagmanager.com/gtag/js?id=" + environment.googleAnalytics didn't work this concatenation在这个地方https://www.googletagmanager.com/gtag/js?id=" + environment.googleAnalytics没有工作这个串联

Need to add google anlytics in your dependencies and then add your tracking code to index.html as discussed in following link.需要在您的依赖项中添加谷歌分析,然后将您的跟踪代码添加到 index.html,如以下链接所述。

npm install --save @types/google.analytics

This link may helps to find a solution.此链接可能有助于找到解决方案。 Go through this thread. Go 通过这个线程。

Angular 4+ using Google Analytics Angular 4+ 使用谷歌分析

You can't write such concatenation because <script> is an html tag, it is not JavaScript code.你不能写这样的连接,因为<script>是一个 html 标记,它不是 JavaScript 代码。 Maybe you'll want to load that script through javascript, in that way you can concatenate your environment.googleAnalytics property.也许您想通过 javascript 加载该脚本,这样您就可以连接您的environment.googleAnalytics属性。

A good way to do this would be to have different index.html files ( index.dev.html , index.prod.html etc.) in which you explicitly define the needed environment variables.一个好的方法是使用不同index.html文件( index.dev.htmlindex.prod.html等),您可以在其中明确定义所需的环境变量。 Then, using the file replacement feature, switch between them (same way that the environment files are replaced).然后,使用文件替换功能,在它们之间切换(与替换环境文件的方式相同)。

"fileReplacements": [
    {
        "replace": "src/index.html",
        "with": "src/index.prod.html"
    }
]

You should create a copy of index.html and name it index.someenv.html.您应该创建 index.html 的副本并将其命名为 index.someenv.html。 Then in your angular.json in environment configuration setup file replacement:然后在您的 angular.json 中的环境配置设置文件替换:

"fileReplacements": [{
    "replace": "src/index.html",
    "with": "src/index.someenv.html"
}]

The angular cli will replace these files when you run your build angular cli 将在您运行构建时替换这些文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM