Quiero usar variables ambientales en mi proyecto angular para ocultar información confidencial. He seguido este tutorial usando dotenv https://javascript.plainenglish.io/setup-dotenv-to-access-environment-variables-in-angular-9-f06c6ffb86c0 pero parece que no puedo obtener ningún valor de mi proceso. env. No puedo entender por qué o cómo.
archivo setenv.ts
const { writeFile } = require('fs'); const { argv } = require('yargs'); // read environment variables from .env file require('dotenv').config(); // read the command line arguments passed with yargs const environment = argv.environment; const isProduction = environment === 'prod'; const targetPath = isProduction ? `./src/environments/environment.prod.ts` : `./src/environments/environment.ts`; if (!process.env.API_KEY || !process.env.ANOTHER_API_KEY) { console.error('All the required environment variables were not provided!'); process.exit(-1); } // we have access to our environment variables // in the process.env object thanks to dotenv const environmentFileContent = ` export const environment = { production: ${isProduction}, APP_ID: "${process.env.APP_ID}", API_KEY: "${process.env.API_KEY}" }; `; // write the content to the respective file writeFile(targetPath, environmentFileContent, function (err) { if (err) { console.log(err); } console.log(`Wrote variables to ${targetPath}`); });paquete.json
"ng": "ng", "config": "npx ts-node ./scripts/setenv.ts", "start": "npm run config -- --environment=dev && ng serve", "build": "npm run config -- --environment=prod && ng build",.env
APP_ID=myAppId API_KEY=myApi_KeyCreo que tu camino está equivocado. La forma en que lo hago es importar el entorno en la parte superior del documento, por ejemplo, con una ruta relativa desde src/app/services/api.service.ts a src/enviroments/environment.ts:
import { environment } from '../../environments/environment';Y luego simplemente extraiga los valores que necesita:
BACKEND_URL = environment.apiUrl;Sospecho que no tiene el archivo .env en el lugar correcto. puedes probar esto
require('dotenv').config({ path: '/custom/path/to/.env' })Ver aquí https://www.npmjs.com/package/dotenv