最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - NX: Angular Environment Variables - process is not defined - Stack Overflow

programmeradmin4浏览0评论

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: /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 (appponent.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
appponent.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 appponent.ts and using dot notation
  • re-reading that doc multiple times
  • tried this doc as well: /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

发布评论

评论列表(0)

  1. 暂无评论