integrate matomo in your Angular project

integrate matomo in your Angular project

I wanted to share the easiest way to integrate https://github.com/matomo-org/matomo in an angular project (tested with angular 7) with zero external package.

Add following structure to angular project

src/
├── analytics
│  ├── conf
│  │  ├── matomo.conf.local.js
│  │  ├── matomo.conf.staging.js
│  │  └── matomo.conf.prod.js
│  ├── matomo.conf.js
│  └── matomo.js

Put your matomo provided script in matomo.js and :
– delimit with: if(matomoEnabled){ ... }.
– replace the matomo url with variable matomoUrl.
– replace the matomo site id by variable matomoSiteId.

if (matomoEnabled) {
  console.log("init matomo { matomoEnabled: " + matomoEnabled + ", matomoUrl: " + matomoUrl + ", matomoSiteId: " + matomoSiteId + " }");
  var _paq = window._paq || [];
  /* tracker methods like "setCustomDimension" should be called before "trackPageView" */
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  (function() {
    var u=matomoUrl;
    _paq.push(['setTrackerUrl', u+'matomo.php']);
    _paq.push(['setSiteId', matomoSiteId]);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
  })();
} else {
  console.log("matomo disabled");
}

In matomo.conf.js:

matomoEnabled=false;
matomoUrl="";
matomoSiteId="";

Copy matomo.conf.js content to matomo.conf.staging.js and matomo.conf.prod.js and fill with environment values.

Then import matomo.js and matomo.conf.js with angular.json:

"angular": {
  "build": {
    "options": {
      ...
      "scripts": [
        "src/analytics/matomo.conf.js",
        "src/analytics/matomo.js"
      ]
      ...
    }
  }
}

Finally use file replacements in angular.json:

"configurations": {
  "prod": {
    "fileReplacements": [
      {
        "replace": "src/analytics/matomo.conf.js",
        "with": "src/analytics/conf/matomo.conf.local.js"
      }
    ]
  }
}
admin

Leave a Reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax