Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access process.env in environment.ts file created from the angular-cli

I have an angular-cli application (angular version 4.0.0). I want to be able to access my environment variables in the environment.ts file created from the cli.

Example:

export SOME_VARIABLE=exampleValue

When I build my angular app I want "exampleValue" to be populated in the SOME_VARIABLE field.

// environment.ts

export const environment = {
    production: false,
    SOME_VARIABLE: process.env.SOME_VARIABLE
};

Unfortunately, process.env isn't available in this file. How can I gain access to it?

like image 371
Blake Avatar asked Apr 19 '17 13:04

Blake


1 Answers

One way to solve this is to create a node script, which replaces a place holder.

This can be done with replace-in-file from npm.

A solution can look like this:

  1. npm install replace-in-file --save-dev

  2. Create a place holder

    export const environment = {
      production: true,
      version: '{BUILD_VERSION}'
    }
    
  3. Create node script to replace the place holder (replace.build.js in root folder)

    var replace = require('replace-in-file');
    var buildVersion = process.env.BUILD_NUMBER;
    const options = {
      files: 'environments/environment.ts',
      from: /{BUILD_VERSION}/g,
      to: buildVersion,
      allowEmptyPaths: false,
    };
    
    try {
      let changedFiles = replace.sync(options);
      console.log('Build version set: ' + buildVersion);
    }
    catch (error) {
      console.error('Error occurred:', error);
    }
    
  4. Execute this node script in your build process f.e. in gulp

    gulp.task('updateVersion', function (done) {
      exec('node ./replace.build.js', function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        done();
      });
    });
    

Now you can use environment.version in your app.

like image 106
Juri Avatar answered Nov 15 '22 04:11

Juri