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:
Versions:
Please let me know if I'm missing anything. Thanks in advance
I was using the EsBuild instructions when I should have been using the Webpack instructions.
The webpack instructions work for the most part but the documentation is missing a variable declaration
module.exports = (config, options, context) => {
config.plugins = config.plugins || []; // Add this line in. Without it, it'll be undefined
config.mode = process.env.NODE_ENV || config.mode;
config.plugins.push(new webpack.DefinePlugin(getClientEnvironment()));
return config;
};
After following the Webpack instructions and adding the commented line above, I was able to get env vars working.