【问题标题】:Access process.env in environment.ts file created from the angular-cli访问从 angular-cli 创建的 environment.ts 文件中的 process.env
【发布时间】:2017-09-15 18:43:30
【问题描述】:

我有一个 angular-cli 应用程序(角度版本 4.0.0)。我希望能够访问从 cli 创建的 environment.ts 文件中的环境变量。

例子:

export SOME_VARIABLE=exampleValue

当我构建我的 Angular 应用程序时,我希望在 SOME_VARIABLE 字段中填充“exampleValue”。

// environment.ts

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

很遗憾,此文件中没有 process.env。我怎样才能访问它?

【问题讨论】:

标签: angular angular-cli


【解决方案1】:

解决此问题的一种方法是创建一个节点脚本,它替换占位符。

这可以通过来自 npm 的replace-in-file 来完成。

解决方案可能如下所示:

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

  2. 创建一个占位符

    export const environment = {
      production: true,
      version: '{BUILD_VERSION}'
    }
    
  3. 创建节点脚本以替换占位符(根文件夹中的replace.build.js)

    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. 在您的构建过程中执行此节点脚本 f.e.一口吞下

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

现在您可以在您的应用中使用environment.version

【讨论】:

  • 我不认为添加gulp 是一个好的解决方案。把事情简单化。我不想再添加太多东西了。它使事情变得复杂
  • @novaline gulp 只是一个例子。使用节点执行此操作。你有更好/更简单的建议吗?
猜你喜欢
  • 2019-07-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-12
  • 2018-07-23
  • 2019-04-04
  • 2019-05-28
  • 1970-01-01
  • 2018-05-30
相关资源
最近更新 更多