如何在 Angular 6 中通过 `ng serve` 设置环境 [英] How to set environment via `ng serve` in Angular 6
问题描述
我正在尝试将我的 Angular 5.2 应用程序更新到 Angular 6.我成功地遵循了 Angular 更新指南中的说明(包括将 angular-cli
更新到 v6),现在我正在尝试通过
I am trying to update my Angular 5.2 app to Angular 6. I successfully followed instructions in the Angular update guide (including the update of angular-cli
to v6), and now I am trying to serve the app via
ng serve --env=local
但这给了我错误:
未知选项:'--env'
Unknown option: '--env'
我使用多种环境(dev/local/prod
),这就是它在 Angular 5.2 中的工作方式.我现在如何在 Angular 6 中设置环境?
I use multiple environments (dev/local/prod
), and this is the way it was working in Angular 5.2. How can I set the environment now in Angular 6?
推荐答案
您需要使用新的 configuration
选项(这适用于 ng build
和 ng服务
以及)
You need to use the new configuration
option (this works for ng build
and ng serve
as well)
ng serve --configuration=local
或
ng serve -c local
如果您查看 angular.json
文件,您会发现您可以更好地控制每个配置(aot、优化器、环境文件等)的设置
If you look at your angular.json
file, you'll see that you have finer control over settings for each configuration (aot, optimizer, environment files,...)
"configurations": {
"production": {
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
]
}
}
您可以在此处获取更多信息,用于管理特定于环境的配置.
You can get more info here for managing environment specific configurations.
正如下面的其他回复中所指出的,如果您需要添加一个新的环境",则需要向 build 任务添加一个新配置,并根据您的需要添加到 <强>服务和测试任务.
As pointed in the other response below, if you need to add a new 'environment', you need to add a new configuration to the build task and, depending on your needs, to the serve and test tasks as well.
添加新环境
编辑:为了清楚起见,必须在 build
部分指定文件替换.因此,如果您想将 ng serve
与特定的 environment
文件(比如 dev2)一起使用,您首先需要修改 build
部分添加新的 dev2 配置
Edit:
To make it clear, file replacements must be specified in the build
section. So if you want to use ng serve
with a specific environment
file (say dev2), you first need to modify the build
section to add a new dev2 configuration
"build": {
"configurations": {
"dev2": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.dev2.ts"
}
/* You can add all other options here, such as aot, optimization, ... */
],
"serviceWorker": true
},
然后修改您的 serve
部分以添加一个新配置,指向您刚刚声明的 dev2 build
配置
Then modify your serve
section to add a new configuration as well, pointing to the dev2 build
configuration you just declared
"serve":
"configurations": {
"dev2": {
"browserTarget": "projectName:build:dev2"
}
然后你可以使用ng serve -c dev2
,这将使用dev2配置文件
Then you can use ng serve -c dev2
, which will use the dev2 config file
这篇关于如何在 Angular 6 中通过 `ng serve` 设置环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!