[英]Why don't I get any value from process.env?
我想在我的角度项目中使用环境变量来隐藏敏感信息。 我已使用 dotenv https://javascript.plainenglish.io/setup-dotenv-to-access-environment-variables-in-angular-9-f06c6ffb86c0遵循本教程,但我似乎无法从我的过程中获得任何价值。环境。 我不知道为什么或如何。
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}`);
});
包.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_Key
我相信你的道路是错误的。 我这样做的方式是在文档顶部导入环境,例如,从 src/app/services/api.service.ts 到 src/enviroments/environment.ts 的相对路径:
import { environment } from '../../environments/environment';
然后只需提取您需要的值:
BACKEND_URL = environment.apiUrl;
我怀疑您没有 .env 文件在正确的位置。 你能试试这个
require('dotenv').config({ path: '/custom/path/to/.env' })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.