Using Environment Variables in Angular (ubuntu)

Abhinav Gupta
2 min readAug 26, 2020

--

Photo by Markus Spiske on Unsplash
Versions:
Angular CLI: 9.1.1
Node: 12.16.1
OS: linux x64
Angular: 9.1.1

Let’s talk about using environment variables in your angular app. Before we begin, let’s add our environment variables, edit your environment file “/etc/environment” and add your environment variable at the end of the file, let’s add a variable name “GREETING” as “hello” in the environment file:

GREETING="hello"

Save the file, and check whether the environment variable is present or not by running “echo $GREETING” in the terminal, it should print “hello” on the terminal.

Let’s start with the angular app now, add the dependencies first, run the following command on terminal in your project’s directory:

npm i -D @angular-devkit/build-angular @angular-builders/dev-server @angular-builders/custom-webpack dotenv

Now find “angular.json” in your project and find @angular-devkit/build-angular:browser and replace it with @angular-builders/custom-webpack:browser it will allow you to use custom webpack config.

Now in the options of the line you just edited in angular.json, add the following:

"options": {
"customWebpackConfig": {
"path": "./extra-webpack.config.js"
}

After that we need to find the “serve” property in angular.json and add a builder in it like the following code:

"serve": {
"builder": "@angular-builders/custom-webpack:dev-server",
"options": {...

Now let’s create a new file in the root folder or project folder with the name extra-webpack.config.js and add the following code in it:

const webpack = require("webpack")
module.exports = {
plugins: [
new webpack.DefinePlugin({
'process.env': {
GREETING: JSON.stringify(process.env.GREETING)
}
})
]
}

Now let’s create a new file named typings.d.ts in the following path:

node_modules/@types/node/typings.d.ts

And add the following code in it:

declare var process: Process;
interface Process {
env: Env
}
interface Env {
GREETING: string
}
interface GlobalEnvironment {
process: Process
}

That’s all, now we can use the environment variables in our code like this:

const greeting = process.env.GREETING

--

--

Abhinav Gupta
Abhinav Gupta

Written by Abhinav Gupta

Abhinav is a software engineer

No responses yet