简体   繁体   中英

angular2-starter config file (with environment (testing, production) variables aka .env or .conf)

In many frameworks like for example PHP Laravel there are files with local configuration (different from dev, test, production environments). How to provide such configuration file which will contain all local environment variables values (like key for Google Analytics, snetry.io etc.) for angular-starter project?

I propose following solution which works also with AoT:

In repository with our angular-starter project in main directory (where is package.json, docker and other top folder files) we create file .env.example.js with following body:

// copy this file to './.env.js' and modify variables in EnvData

var Env = {
    // If some of below variable is NULL then that varabile feature is off
    google_analaytics : 'XX-YYYYYYYY-Z',
    sentry_clientKey_publicDSN: 'https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@sentry.io/yyyyyy',
    // ... here you can put more variables
};

module.exports = Env;

Then we copy this file to .env.js and include that last one to .gitignore file. And then we commit files .env.example.js and .gitignore into our git repository.

We use .js file instead of .ts (typescript) because on generating index.html file webpack works on js files. Ok so let's show how use this variables in webpack config files. Let's go to ./config/webpack.common.js and find below code and add line:

  new HtmlWebpackPlugin({
    template: 'src/index.html',
    title: METADATA.title,
    chunksSortMode: 'dependency',
    metadata: METADATA,
    inject: 'head',
    env: require('../.env')    // <-- new line
  }),

Then in ./src/index.html in google analytics section you can change to:

  <% if (htmlWebpackPlugin.options.env.google_analaytics) { %>
  <!-- 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_analaytics %>', 'auto');
    ga('send', 'pageview');
  </script>
  <% } %>

And inside you typescript module/component/class (.ts file) you can use variable value (we import js into ts) in such way (below example is for setup sentry):

import * as Raven from 'raven-js'; // http://sentry.io
import * as Env  from '../../.env.js';
...
let sentryDSN = Env['sentry_clientKey_publicDSN']
if(sentryDSN)
{
    Raven.config(sentryDSN).install();
    ...
}
...

Thats all :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM