访问从 angular-cli 创建的 environment.ts 文件中的 process.env [英] Access process.env in environment.ts file created from the angular-cli
问题描述
我有一个 angular-cli 应用程序(Angular 版本 4.0.0).我希望能够访问从 cli 创建的 environment.ts 文件中的环境变量.
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.
示例:
export SOME_VARIABLE=exampleValue
当我构建我的 Angular 应用程序时,我希望在 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
};
不幸的是,process.env 在此文件中不可用.我如何才能访问它?
Unfortunately, process.env isn't available in this file. How can I gain access to it?
推荐答案
解决此问题的一种方法是创建一个节点脚本,该脚本替换占位符.
One way to solve this is to create a node script, which replaces a place holder.
这可以通过 npm 的 replace-in-file 来完成.
This can be done with replace-in-file from npm.
解决方案可能如下所示:
A solution can look like this:
npm install replace-in-file --save-dev
npm install replace-in-file --save-dev
创建占位符
Create a place holder
export const environment = {
production: true,
version: '{BUILD_VERSION}'
}
创建节点脚本以替换占位符(根文件夹中的replace.build.js)
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);
}
在您的构建过程中执行此节点脚本,例如吞咽
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();
});
});
现在您可以在您的应用中使用 environment.version
.
Now you can use environment.version
in your app.
这篇关于访问从 angular-cli 创建的 environment.ts 文件中的 process.env的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!