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

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

Example:

export SOME_VARIABLE=exampleValue 

When I create an angular application, I want the "exampleValue" to be filled in the SOME_VARIABLE field.

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

Unfortunately, process.env is not available in this file. How can I access it?

+5
source share
1 answer

One way to solve this problem is to create a node script that replaces the owner’s place.

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

The solution might look like this:

  • npm install replace-in-file --save-dev

  • Create a place owner

     export const environment = { production: true, version: '{BUILD_VERSION}' } 
  • Create a node script to replace the owner of the place (replace.build.js in the 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); } 
  • Run this node script during fe build process 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 application.

+1
source

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


All Articles