Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ibnsamy96/98e37b628f42fb1c42f688e05571b599 to your computer and use it in GitHub Desktop.
Save ibnsamy96/98e37b628f42fb1c42f688e05571b599 to your computer and use it in GitHub Desktop.

I faced a problem that I couldn't use vercel environment variables with a deployed angular app. I used to write my sensitive information in an env file while writing backend code and I forgot that browsers don't support the process module. So I searched for a while and got the result I want by following these steps:

  1. install the next package:
    npm install --save-dev @angular-builders/custom-webpack
    
  2. open angular.json and use "builder": "@angular-builders/custom-webpack:browser" instead of "builder": "@angular-devkit/build-angular:browser"
  3. add customWebpackConfig key in options object with a path to a file that you will create later:
     "options": { "customWebpackConfig": {"path": "custom-webpack-config.js"} }
  4. create a new file in the root directory with the name custom-webpack-config.js and add this code in it:
    const webpack = require("webpack");
     module.exports = {
       plugins: [
         new webpack.DefinePlugin({
           $env: {
             API_KEY: JSON.stringify(process.env.API_KEY),
             LOCATION_API_KEY: JSON.stringify(process.env.LOCATION_API_KEY),
           },
         }),
       ],
     };
  5. and create another file in the src directory with the name typing.d.ts and this code in it:
    import { CoreEnvironment } from '@angular/compiler/src/compiler_facade_interface';
    declare var $env: ENV;
    interface ENV {
      API_KEY: string;
      LOCATION_API_KEY: string;
    }
  6. now add the vars to the environment.prod.ts file and use them as you want around the project:
    import { $env } from 'src/typing.d';
    export const environment = {
      production: true,
      API_KEY: $env.API_KEY,
      LOCATION_API_KEY: $env.LOCATION_API_KEY,
    };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment