更改angular默認端口號的正確方式


Angular 的默認端口號是 4200。

在 webstorm 中開啟終端 Terminal 后輸入命令 npm start 即可編譯該項目:

從上圖中提示可知,也就是編譯通過后,在瀏覽器中輸入 localhost:4200 即可打開項目。

 

在我們實際項目中可能有兩個或多個項目在一起開發和維護(例如我在邊學邊做 Angular 項目,有一個 demo 用來學習和測試功能,另有一個真實的項目),在這種情況下,在編譯時就會報錯,提示 4200 端口被占用了:

所以我們就需要更改端口號。

 

在網上查詢過更改端口號的方法,幾乎所有的帖子、論壇(參考的其中一篇文章:http://blog.csdn.net/qq_24734285/article/details/54962479)都指明了兩種方法:

1. 通過命令 ng serve --port 4203  (4203是想要更改的端口號)

2. 通過 Angular 模塊的配置文件 schema.json(我的路徑是:node_modules/@angular/cli/lib/config/schema.json) 來更改: 

"serve": {
  "description": "Properties to be passed to the serve command.",
  "type": "object",
  "properties": {
    "port": {
      "description": "The port the application will be served on.",
      "type": "number",
      "default": 4200
    },
    "host": {
      "description": "The host the application will be served on.",
      "type": "string",
      "default": "localhost"

    },
    "ssl": {
      "description": "Enables ssl for the application.",
      "type": "boolean",
      "default": false

    },
    "sslKey": {
      "description": "The ssl key used by the server.",
      "type": "string",
      "default": "ssl/server.key"

    },
    "sslCert": {
      "description": "The ssl certificate used by the server.",
      "type": "string",
      "default": "ssl/server.crt"
    }
  }
}

上面代碼中 "port" 對象的 "default" 屬性指明了 Angular 的默認端口號,更改成你想要的端口號即可。

不建議這種做法,因為:

1. 相當於你去更改源代碼,更改別人提供給你的接口。這樣的文件你需要的是拿來使用而不是暴力更改。

2. 另一方面當我試圖去更改時,webstorm 提示我該文件不屬於這個項目:

既然它都不屬於這個項目,我們就沒有資格去更改它。

那第一種方法合不合適呢?我們試試就知道了:

編譯通過

並且在瀏覽器中順利打開該項目。看來是可行的,可是?!

當我們在 webstorm 中關掉該項目(有很多場景都會出現這種情況:1.比如下班了關機,2.比如電腦卡慢關掉這個項目)之后再打開,輸入命令 npm start 那時他又會報錯,說端口號被占用。我們不得不又輸入命令 ng serve --port 4203 來啟動該項目。

 

總結:這兩種方法都不推薦使用,第一種通過命令的方式如果是暫時用來驗證臨時用用無所謂,真實的項目中用的話,除非你想每次都那么麻煩的輸入多余的一長串命令(無論是手動輸入還是使用上下鍵調出)。 


 

那么還有沒有其它的方法呢?那就真實進入今天的主題,如何正確的更改:

Angular 提供了配置文件用來更改基本的配置,在根文件夾下的 package.json 文件

該文件中, "scripts" 對象的初始值是:

"scripts": {
  "ng": "ng",
  "start": "ng serve",
  "build": "ng build",
  "test": "ng test",
  "lint": "ng lint",
  "e2e": "ng e2e"
},

這里有一個 "start" 屬性,更改這里的值:

"scripts": {
  "ng": "ng",
  "start": "ng serve --port 4203 --env=dev",
  "build": "ng build --env=prod",
  "test": "ng test",
  "lint": "ng lint",
  "e2e": "ng e2e"
},

然后在 webstrom 的終端 Terminal 里輸入命令 npm start 就能編譯通過並且在瀏覽器中順利打開了。

 

總結:更改 Angular 默認端口號的正確方式,是更改根文件夾下的 package.json 配置文件,將 "scripts" 對象的 "start" 屬性的值更改成你想要的端口號。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM