访问从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
构建我的角度应用程序时,我希望在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中的替换在文件中完成.
This can be done with replace-in-file from npm.
解决方案如下:
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屋!