Here is a solution that is compatible with AoT (Ahead of Time Compilation):
To make this work, create a file named .env.example.js
in the main directory of your angular-starter project (where you find package.json, docker, and other top-level files). The contents of the file should look like this:
// Copy this file to './.env.js' and modify variables in EnvData
var Env = {
google_analytics: 'XX-YYYYYYYY-Z',
sentry_clientKey_publicDSN: 'https://[email protected]/yyyyyy',
// Add more variables here
};
module.exports = Env;
Copy this file as .env.js
and add it to the .gitignore
file. Then commit both .env.example.js
and .gitignore
to your git repository.
We are using .js files instead of .ts (typescript) because webpack works on js files when generating the index.html
file. Now, let's see how to use these variables in webpack configuration files. Navigate to ./config/webpack.common.js
, find the code snippet below, and add the new line:
new HtmlWebpackPlugin({
template: 'src/index.html',
title: METADATA.title,
chunksSortMode: 'dependency',
metadata: METADATA,
inject: 'head',
env: require('../.env') // <-- new line
}),
In ./src/index.html
, update the Google Analytics section like so:
<% if (htmlWebpackPlugin.options.env.google_analytics) { %>
<!-- Google Analytics: -->
<script>
(function(A,n,g,u,l,a,r){A.GoogleAnalyticsObject=r;A[l]=A[l]||function(){
(A[l].q=A[l].q||[]).push(arguments)},A[l].l=1*new Date();a=n.createElement(g),
r=n.getElementsByTagName(g)[0];a.async=1;a.src=u;r.parentNode.insertBefore(a,r)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', '<%= htmlWebpackPlugin.options.env.google_analytics %>', 'auto');
ga('send', 'pageview');
</script>
<% } %>
In your typescript module/component/class (.ts file), you can access variable values by importing the js file. Here's an example for setting up Sentry:
import * as Raven from 'raven-js';
import * as Env from '../../.env.js';
...
let sentryDSN = Env['sentry_clientKey_publicDSN']
if(sentryDSN)
{
Raven.config(sentryDSN).install();
...
}
...
That's all for now :)