NX: Angular Environment Variables - process is not defined

Discussão em 'Angular' iniciado por Freigheist, Fevereiro 19, 2025.

  1. Freigheist

    Freigheist Guest

    I have a NX project with an angular app. I'd like to configure a environment variable so that some value changes depending on the deployment environment. I'm following the NX Recipe documentation for this topic: https://nx.dev/recipes/angular/use-environment-variables-in-angular

    I seem to be following it exactly but, when I get to the browser, I'm getting the following error in the console.

    ERROR ReferenceError: process is not defined
    at new AppComponent (app.component.ts:14:28)


    The only difference in what I'm doing is that I've used the @nx/angular:browser-esbuild executor instead of the @nx/angular:application . But the docs say you can use both.

    project.json

    "executor": "@nx/angular:browser-esbuild",
    ...
    "plugins": ["apps/debug-nx-ng/plugins/env-var-plugin.js"],


    Here are my other changes but they are copied from the guide, some with minor modifications.

    types.d.ts

    declare const process: {
    env: {
    [key: string]: string;
    };
    };



    env-var-plugin.js

    const myOrgEnvRegex = /^MY_ORG_/i;

    const envVarPlugin = {
    name: 'env-var-plugin',
    setup(build) {
    const options = build.initialOptions;

    const envVars = {};
    for (const key in process.env) {
    if (myOrgEnvRegex.test(key)) {
    envVars[key] = process.env[key];
    }
    }

    options.define['process.env'] = JSON.stringify(envVars);
    },
    };

    module.exports = envVarPlugin;



    .env

    MY_ORG_LOREM_IPSUM=foobar


    app.component.ts


    export class AppComponent {
    title = 'debug-nx-ng';
    constructor() {
    console.log('env-var', process.env['MY_ORG_LOREM_IPSUM']);
    }
    }


    It compiles and lints correctly but when I navigate to localhost:4200, I get the error in the browser.

    I've tried:

    • relative paths and absolute paths in project.json
    • ensured paths are correct and files are in the right place
    • creating a new project and starting over
    • originally, i had a env-var.ts file but I converted it to js
    • tried other forms of plugins and formats
    • declare const process: any; in my app.component.ts and using dot notation
    • re-reading that doc multiple times
    • tried this doc as well: https://nx.dev/nx-api/angular/executors/browser-esbuild

    Versions:

    • NX Local: v20.4.5 | Global: v20.0.0
    • Node v18.20.4
    • Angular v19.1.0

    Please let me know if I'm missing anything. Thanks in advance

    Continue reading...

Compartilhe esta Página