在 Angular 项目中,默认情况下,只有生产环境(prod)被使用。如果你想在开发环境(dev)或测试环境(test)中使用不同的环境,你需要对 Angular 项目进行配置。
假设你在项目中使用 Angular CLI 工具,你可以通过以下步骤解决这个问题:
首先,创建对应的环境文件。在项目根目录下,可以找到一个 /src/environments
文件夹,里面有一个 environment.prod.ts
文件。你需要创建两个新的环境文件 environment.dev.ts
和 environment.test.ts
。
修改 angular.json
文件。在该文件中找到 "configurations"
对象,为 dev 和 test 环境增加相应的配置信息。例如:
{
"projects": {
"your-project-name": {
"architect": {
"build": {
"configurations": {
"dev": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.dev.ts"
}
]
},
"test": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.test.ts"
}
]
}
}
}
}
}
}
}
environment.ts
和你新增的两个环境文件中,分别定义你需要使用的环境变量。例如:// environment.ts
export const environment = {
production: false,
apiUrl: 'https://dev.api.com'
};
// environment.dev.ts
export const environment = {
production: false,
apiUrl: 'https://dev.api.com'
};
// environment.test.ts
export const environment = {
production: false,
apiUrl: 'https://test.api.com'
};