2

I'm trying to implement Google Analytics. I have different tracking codes for each of my environments (dev, prod, etc). I don't have access to environments.ts from index.html as far as I know.

I tried loading the script from inside Angular, but then I lost tracking of how long the app's initial load took. I also saw that .angular-cli.json has a scripts section that I could possibly use, but I don't know how I'd switch which script I run based on the environment.

How can I set this up?

3
  • You can't access environment variables there. It's just a static file. Try using something like Angulartics. Commented Jul 14, 2017 at 15:08
  • I am. Angulartics tells me to put my GA script tag in index.html and doesn't mention environments in their documentation at all. Commented Jul 14, 2017 at 15:12
  • See e.g. github.com/angulartics/angulartics2/issues/106 Commented Jul 14, 2017 at 15:13

2 Answers 2

1

For Angular 8 or above version just modify the production:configuration section in angular.json as below

    "build": {
      "builder": "@angular-devkit/build-angular:browser",
      "options": {
        "index": "src/index.html"
      },
      "configurations": {
        "production": {
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.prod.ts"
            }
          ],
          "index": "src/index.prod.html"
        }
      }
    }

Hope this answer helps.

Regards, Kirti Singh | Soluzione IT Services

Sign up to request clarification or add additional context in comments.

Comments

0

As of Angular 6 you can configure file replacements in angular.json:

"configurations": {
  "dev": {
    ...
    "fileReplacements": [
      {
        "replace": "src/myScripts.js",
        "with": "src/myScripts.dev.js",
      }
    ]
  },
  "production": {
    ...
    "fileReplacements": [
      {
        "replace": "src/myScripts.js",
        "with": "src/myScripts.prod.js",
      }
    ]
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.