Skip to content

Instantly share code, notes, and snippets.

@quinnjr
Last active August 22, 2024 09:33
Show Gist options
  • Save quinnjr/6ef72d6c3ba755125ac64da2677c5c52 to your computer and use it in GitHub Desktop.
Save quinnjr/6ef72d6c3ba755125ac64da2677c5c52 to your computer and use it in GitHub Desktop.
How to easily add environment variables to an Angular application

How to easily add environment variables to an Angular application

This guide assumes that you already have an angular application set up by ng create and are using Angular CLI for compilation.

Other guides that I've read rely upon re-writing your environments/environment.ts|environment.prod.ts files with each compilation. I find this to be completely unnecessary when angular's internal use of webpack can just be extended to include environment variables.

1. Add @angular-builders/custom-webpack to your dev-dependencies

$ npm i -D @angular-builders/custom-webpack

1.a. Add dotenv to your dev-dependencies

I use dotenv to load .env file variables on my development machine. It is not required to install, but is useful while developing locally.

$ npm i -D dotenv

2. Create a custom webpack configuration

For example, create a file custom-webpack.config.js in the root of your project.

After creating the custom webpack file, add the following contents (or more) to the file.

const { EnvironmentPlugin } = require('webpack');
// Add additional requirements here

// If you're using dotenv
require('dotenv').config()

// Export a configuration object
// See [Wepack's documentation](https://webpack.js.org/configuration/) for additional ideas of how to 
// customize your build beyond what Angular provides.
module.exports = {
  plugins: [
    new EnvironmentPlugin([
      // Insert the keys to your environment variables here.
      // Eg: APP_API_ENDPOINT="http://localhost:3000/api/v1"
      APP_API_ENDPOINT
    ])
}

3. Add @angluar-builder/custom-webpack to your build scheme

In the fileangular.json, find the key projects.${YOUR PROJECT NAME}.architect.build and change it to:

...
"architect": {
  ...
  "build": {
    "builder: "@angular-builders/custom-webpack:browser",
    "options: {
      "path": "./custom-webpack.config.js",
      "replaceDuplicatePlugins": true
    }
    ...
  }
  ...
}
...

3.a Add @angular-builders/custom-webpack's development server

If you're using ng serve in developemnt, you may wish to also install the custom development server.

$ npm i -D @angular-builders/dev-server

And in your angular.json file, replace the dev server invocation to:

...
"architect": {
  ...
  "serve": {
    "builder": "@angular-builders/dev-server:dev-server",
    ...
  }
  ...
}
...

4. Use process.env to input your environment variables at compilation.

Perform the same steps as you'd use normally for the webpack EnvironmentPlugin.

Eg:

@Injectable()
export class ApiService {
  private readonly api = process.env.APP_API_ENDPOINT;
  
  constructor(private http: HttpClient) {  }
  
  public get(loc: string): Observable<any> {
    return this.http.get(api + loc);
  }
}
// Copyright (c) 2020 Joseph R. Quinn
// SPDX-License-Identifier: ISC
const { EnvironmentPlugin } = require('webpack');
const SriPlugin = require('webpack-subresource-integrity');
require('dotenv').config();
module.exports = {
output: {
crossOriginLoading: 'anonymous'
},
plugins: [
new SriPlugin({
hashFuncNames: ['sha384'],
enabled: true
}),
new EnvironmentPlugin([
'APP_BACKEND_API_ENDPOINT'
'GITHUB_OAUTH_TOKEN'
])
]
}
@meSmashsta
Copy link

For the recent version of webpack you need to adjust the config like so:
image

@dg98
Copy link

dg98 commented Jan 9, 2024

Thanks for the tutorial. I just noticed that @angular-builders/dev-server didn't update for 5 years and couldn't be used with a current angular version. I used @angular-builders/custom-webpack:dev-server as the builder for serve which is included in the custom-webpack package

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment