angular-cli server - how to specify default port

前端 未结 8 1012
星月不相逢
星月不相逢 2020-12-04 10:42

Using angular-cli with the ng serve command, how can I specify a default port so I do not need to manually pass the --port flag every time?

8条回答
  •  爱一瞬间的悲伤
    2020-12-04 11:01

    There might be a situation when you want to use NodeJS environment variable to specify Angular CLI dev server port. One of the possible solution is to move CLI dev server running into a separate NodeJS script, which will read port value (e.g from .env file) and use it executing ng serve with port parameter:

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

    Then you may a) run this script directly via node run-env, b) run it via npm by updating package.json, for example

    "scripts": {
      "start": "node run-env"
    }
    

    run-env.js should be committed to the repo, .env should not. More details on the approach can be found in this post: How to change Angular CLI Development Server Port via .env.

提交回复
热议问题