我想在我的angular项目中使用环境变量来隐藏敏感信息。我使用dotenv https://javascript.plainenglish.io/setup-dotenv-to-access-environment-variables-in-angular-9-f06c6ffb86c0遵循本教程,但我似乎无法从process.env中获得任何价值。我不知道为什么,也不知道怎么回事。
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}`);
});
package.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的相对路径。链接到src/environments/environments . Ts:
import { environment } from '../../environments/environment';
然后提取你需要的值:
BACKEND_URL = environment.apiUrl;
我怀疑您没有将.env文件放在正确的位置。你能试试这个吗
require('dotenv').config({ path: '/custom/path/to/.env' })
见这里https://www.npmjs.com/package/dotenv