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

别来无恙 提交于 2020-01-02 03:06:12

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/43497373/access-process-env-in-environment-ts-file-created-from-the-angular-cli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!