How to incorporate Google Analytics into an Angular Cli app

Typically, the inclusion of analytics involved inserting the tracking code into the html body with the property identifier and the page view action. I followed the answer in Tracking Google Analytics page views in Angular2 , and when ng serve executed, it correctly includes the script, but then when creating the production object, it is not included in the index:

 ng build --progress false --aot true -prod -e prod 

What is the best practice of incorporating Google Analytics or another tracking solution using Angular2 Cli?

Thank you in advance

+8
source share
2 answers

You can link it to the rest of your scripts using Angular -CLI.

Put the Google analytics code in a file called google-analytics.js . Make sure you remove the script tags.

Then, in your angular-cli.json file, add your google-analytics.js file to the scripts property.

Here is an example of how the code will look in angular-cli.json .

 "scripts": [ "google-analytics.js" ], 

This snippet will call Angular-cli to merge google-analytics into a file called scripts.bundle.js , which is loaded at run time by the ng serve command.

+5
source

Angular Version 7: One way to include some environment-specific js is to

  1. save the script in some way: For example: src/assets/javascripts/prod.js

  2. Then, in angular.json find the build configuration for the specific configuration (see: here ) and in the desired environment add an additional array of scripts.

  3. ng build --prod will also bundle an additional script.

The example below uses the production environment for demonstration, but this can be done for any environment.

Sample angular.json below. Tested on Angular 7 (Please refer only to the "scripts" key inside the assembly configuration, the file has been changed a lot to show only the corresponding part)

 { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "test": { "root": "", "sourceRoot": "src", "projectType": "application", "prefix": "app", "schematics": {}, "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": {}, "configurations": { "production": { "scripts": ["src/assets/javascripts/prod.js"] } } } } } }, "defaultProject": "test" } 
0
source

Source: https://habr.com/ru/post/1264561/


All Articles