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?
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:
npm install replace-in-file --save-dev
Create a place holder
export const environment = {
production: true,
version: '{BUILD_VERSION}'
}
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();
});
});
Now you can use environment.version
in your app.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With