我想用5000而不是4200。

我尝试在根名称ember-cli上创建一个文件,并按照下面的代码放置JSON:

{
   "port": 5000
}

但我的应用程序仍然运行在4200,而不是5000


当前回答

如果你想使用NodeJS环境变量来设置Angular CLI开发服务器的端口值,可以采用以下方法:

创建NodeJS脚本,该脚本可以访问环境变量(比如DEV_SERVER_PORT),并可以运行ng serve,使用该变量的——port参数值(child_process可能是我们的朋友):

const child_process = require('child_process');
const child = child_process.exec(`ng serve --port=${process.env.DEV_SERVER_PORT}`);
child.stdout.on('data', data => console.log(data.toString()));

更新包。Json提供这个脚本通过NPM运行 不要忘记设置DEV_SERVER_PORT环境变量(可以通过dotenv完成)

下面是对这种方法的完整描述:如何通过.env更改Angular CLI开发服务器端口。

其他回答

要在运行时更改一次端口,并且没有更改配置,您可以使用以下命令

ng serve --port 5000

如果每次运行ng服务都需要5000端口。使用以下方法

使用angular.json

在“选项”字段下搜索“服务”,如下所示:

在node_modules > @angular-devkit > build-angular > src > dev-server > schema中。Json,你会发现下面的代码和更新端口,如你想要的5000。 在包中。Json下的“脚本”,我们已经“开始”更新它与下面的命令,所以每次运行“npm开始”,它将服务于5000。

注意:在终端中使用'ng serve'或'npm start'发布所有的重启服务器反馈有助于改进。谢谢!

虽然上面的答案中已经有很多有效的解决方案,但这里是一个使用visual Studio Code的Angular 7项目的可视化指南和具体解决方案(也可能是更早的版本,但不保证)。定位模式。在图像树中显示的目录中添加Json,并更改port——> default下的整数,以永久更改浏览器中的端口。

转到这个文件

node_modules\@angular-devkit\build-angular\src\dev-server\schema.json

搜索端口

"port": {
  "type": "number",
  "description": "Port to listen on.",
  "default": 4200
},

更改默认值并重新启动服务器

转到angular。json文件,

搜索关键字“serve”:

添加port关键字如下所示:

 "serve": {
     "builder": "@angular-devkit/build-angular:dev-server",
     "options": {
         "browserTarget": "my-new-angular-app:build",
         "port": 3001
     },
     ...

如果你想使用NodeJS环境变量来设置Angular CLI开发服务器的端口值,可以采用以下方法:

创建NodeJS脚本,该脚本可以访问环境变量(比如DEV_SERVER_PORT),并可以运行ng serve,使用该变量的——port参数值(child_process可能是我们的朋友):

const child_process = require('child_process');
const child = child_process.exec(`ng serve --port=${process.env.DEV_SERVER_PORT}`);
child.stdout.on('data', data => console.log(data.toString()));

更新包。Json提供这个脚本通过NPM运行 不要忘记设置DEV_SERVER_PORT环境变量(可以通过dotenv完成)

下面是对这种方法的完整描述:如何通过.env更改Angular CLI开发服务器端口。