Passing a secret key inside the env file won't make it private it will remain public thus I have a solution for you where you could read a key from environment variable without mentioning it in environment.ts
to do this you'll need to install few dependencies.
these are the versions that are compatibles with Angular 7
probably few other you are free to try new versions.
"@angular-builders/custom-webpack": "^7.2.0",
"@angular-builders/dev-server": "^7.2.1",
"@angular-devkit/build-angular": "^0.12.3"
run
npm i @angular-builders/custom-webpack@7.2.0 @angular-builders/dev-server@7.2.1 @angular-devkit/build-angular@0.12.3
To be able to use custom web pack will have to add some changes to angular.json
under your root
folder
"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig":{
"path": "./extra-webpack.config.js"
},
"serve": {
"builder": "@angular-builders/dev-server:generic",
create a file extra-webpack.config.js
under your root folder and add this inside:
const webpack = require('webpack');
module.exports = {
plugins: [new webpack.DefinePlugin({
'process.env': {
KEY_TO_READ: JSON.stringify(process.env.KEY_TO_READ),
}
})]
}
UPDATE
This also could cause you some troubles so if it works without the typings.d.ts it's better because you'll probably get an error later when everything is working fine declare var process nodejs.process error Variable 'process' must be of type 'Process', but here has type 'Process'.
in that case just use the node types and delete the file typing.d.ts
If you try to use these variables, angular will complain about types definition. To get around that, create a file called typings.d.ts
(d
extension for declare
) inside of your *src/
and put the following in there:
declare var process: Process;
interface Process {
env: Env
}
interface Env {
KEY_TO_READ: string
}
it's better to centralize your config in only the environment.ts
file and use it this way
const KEY = `${process.env.KEY_TO_READ}`;
export const environment = {
production: false,
key : KEY
};
In order to make this work you need to run your app by running this command
KEY_TO_READ="TEST" npm start
you are now able to use the env variable inside your angular app in a someservice.ts
const Hash = `${environment.key}`;
export class SomeService{
console.log(Hash) //should display "TEST" in your console
}
Hope it helps.