簡體   English   中英

在 index.html 中使用環境變量

[英]Use environement variable in index.html

我正在使用 angular 並且我想在我的 index.html 中使用環境變量進行谷歌分析。 我試過這樣:

<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>

但不能在腳本的鏈接中工作。 你能幫我嗎? 在這個地方https://www.googletagmanager.com/gtag/js?id=" + environment.googleAnalytics沒有工作這個串聯

需要在您的依賴項中添加谷歌分析,然后將您的跟蹤代碼添加到 index.html,如以下鏈接所述。

npm install --save @types/google.analytics

此鏈接可能有助於找到解決方案。 Go 通過這個線程。

Angular 4+ 使用谷歌分析

你不能寫這樣的連接,因為<script>是一個 html 標記,它不是 JavaScript 代碼。 也許您想通過 javascript 加載該腳本,這樣您就可以連接您的environment.googleAnalytics屬性。

一個好的方法是使用不同index.html文件( index.dev.htmlindex.prod.html等),您可以在其中明確定義所需的環境變量。 然后,使用文件替換功能,在它們之間切換(與替換環境文件的方式相同)。

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

您應該創建 index.html 的副本並將其命名為 index.someenv.html。 然后在您的 angular.json 中的環境配置設置文件替換:

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

angular cli 將在您運行構建時替換這些文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM