我可以在 ng serve 上将变量传递给 environment.ts 吗?
Can I pass a variable to environment.ts on ng serve?
我经常 运行 一个具有两种不同配置的本地项目。一个带有存根数据,一个连接到 Spring 引导后端。我可以通过以下逻辑在这些模式之间切换 connectToBackend=true
.
// Angular 11, src/environments/environment.ts
import processStubs from '[REDACTED]';
import processBackend from '[REDACTED]';
import { Launcher } from '[REDACTED]';
let connectToBackend = false;
let processLocal;
if (connectToBackend) {
processLocal = processBackend;
} else {
processLocal = processStubs;
}
export const environment = {
process: processLocal,
launcher: Launcher,
production: false,
backendConnection: connectToBackend,
};
如何让connectToBackend
成为项目服务时命令行设置的动态变量?例如:
ng serve --connectToBackend=true
ng serve命令接受参数configuration
.
您可以在 angular 中拥有多个环境 (正如其他人在评论中所建议的那样)。
在angular.json
中你可以提到一个可以覆盖默认环境文件的新环境配置。 (引用自 )
"build": {
"configurations": {
"production": {
// ...
},
"demo": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.demo.ts"
}
]
}
}
}
"serve": {
"configurations": {
"production": {
// ...
},
"demo": {
"browserTarget": "PROJECTNAME:build:demo"
}
}
}
创建一个新文件 src/environments/environment.demo.ts
来存储 backendConnection
变量的值(以及其他必要的变量)
export const environment = {
process,
launcher: Launcher,
production: false,
backendConnection: true
};
对于运行新环境,可以使用这样的命令
ng serve -c=demo
.
我经常 运行 一个具有两种不同配置的本地项目。一个带有存根数据,一个连接到 Spring 引导后端。我可以通过以下逻辑在这些模式之间切换 connectToBackend=true
.
// Angular 11, src/environments/environment.ts
import processStubs from '[REDACTED]';
import processBackend from '[REDACTED]';
import { Launcher } from '[REDACTED]';
let connectToBackend = false;
let processLocal;
if (connectToBackend) {
processLocal = processBackend;
} else {
processLocal = processStubs;
}
export const environment = {
process: processLocal,
launcher: Launcher,
production: false,
backendConnection: connectToBackend,
};
如何让connectToBackend
成为项目服务时命令行设置的动态变量?例如:
ng serve --connectToBackend=true
ng serve命令接受参数configuration
.
您可以在 angular 中拥有多个环境 (正如其他人在评论中所建议的那样)。
在angular.json
中你可以提到一个可以覆盖默认环境文件的新环境配置。 (引用自
"build": {
"configurations": {
"production": {
// ...
},
"demo": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.demo.ts"
}
]
}
}
}
"serve": {
"configurations": {
"production": {
// ...
},
"demo": {
"browserTarget": "PROJECTNAME:build:demo"
}
}
}
创建一个新文件 src/environments/environment.demo.ts
来存储 backendConnection
变量的值(以及其他必要的变量)
export const environment = {
process,
launcher: Launcher,
production: false,
backendConnection: true
};
对于运行新环境,可以使用这样的命令
ng serve -c=demo
.