Well after lot of research and went through lot of blogs, I finally able to implement this. First thing was I was not able to use process.env in typescript and access my environment variables
Step 1 - Create a custom-config.js at the same folder as in package.json
const webpack = require('webpack')
module.exports = {
plugins: [
new webpack.DefinePlugin({
'process.env': {
apiURL: JSON.stringify(process.env.apiURL)
}
})
]
}
Step 2 - Create a typings.d.ts at the same folder as in custom-config.js, to expose the env interface to be available for typescript
declare var process: NodeJS.Process;
interface Process {
env: Env
}
interface Env {
apiURL: string;
}
interface GlobalEnvironment {
process: Process;
}
Step 3 - Install npm Packages.
Need to install npm packages @angular-builders/custom-webpack , @angular-builders/dev-server, @angular-devkit/build-angular and dotenv
Step 4 - Update the default builder to custom builder in angular.json
"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "extra-webpack.config.js"
},
Step 5 - Make sure to update the build option of serve as well in angular.json
"serve": {
"builder": "@angular-builders/dev-server:generic",
Finally I could use this in my Type Script process.env['apiURL'], once I have set my environment variable. Otherwise I get the value as undefined
*NOTE : I always had to restart my system (OS: Windows 10) in order for me to get the values available in my Application. I will still have to go dig more to find out this issue or a work around.
Update : Apparently I do not need to restart my system. just restarting the IDE will do.