I have an Angular 18 app and need to inject environment variable values from a .env file into my environment.ts file and environment.development.ts. I want the values available during development (ng serve) and builds (ng build).
The builder in my angular.json is @angular/build:application
My example environment TS files look like and my plan is to access .env something like this:
export const environment = {
name: 'production',
key: process.env['MYKEY_PROD']
};
and
export const environment = {
name: 'development',
key: process.env['MYKEY_DEV']
};
and .env file looks like:
MYKEY_DEV=123
MYKEY_PROD=456
I cannot directly do this since it is not supported I think. I get error:
de? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig. [plugin angular-compiler]
src/environments/environment.development.ts:3:9:
3 │ key: process.env['MYKEY_DEV']
╵ ~~~~~~~
I found a Medium article which uses a package @angular-builders/custom-webpack. Here is the demo with custom webpack (manually add the .env file if it is not there). I don't want to use Webpack because new Angular uses Vite. Maybe I can make use of it somehow?
.envfiles rather thanenvironment.tsfiles?read-env-filewhich doesn't require global Node.js types. I'm not familiar with Angular's build process so am not entirely sure this will work the way you want, but if you try it and it seems legit then I'll type up an answer..envfile at runtime in the browser then that's not possible without more machinery. How would the.envfile get there? You'd have to set up your server to make it available over HTTP. It's also going to be bad from a security standpoint if you have any secrets in there (which is common with.envfiles). Please edit your question to describe what you want to happen in more detail.