什么时候用'npm start',什么时候用'ng serve'?

When to use 'npm start' and when to use 'ng serve'?

ng serve serves an Angular project via a development server

npm start runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js.

似乎 ng serve 启动了嵌入式服务器,而 npm start 启动了节点服务器。

有人可以解释一下吗?

npm start 将 运行 您为 package.json 文件中 scripts 对象的 start 命令定义的任何内容。

所以如果它看起来像这样:

"scripts": {
  "start": "ng serve"
}

然后 npm start 将 运行 ng serve.

来自文档

npm-start :

此 运行 是在其 "scripts" 对象的包 "start" 属性 中指定的任意命令。如果在"scripts"对象上没有指定"start"属性,它将运行结点server.js.

这意味着它将调用 package.json

中的启动脚本
"scripts": {
"start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite --baseDir ./app --port 8001\" ",
"lite": "lite-server",
 ...
}

ng serve:

由 angular/angular-cli 提供,用于启动 angular2 由 angular-cli 创建的应用程序。当你安装 angular-cli 时,它会在 C:\Users\name\AppData\Roaming\npm 下创建 ng.cmd(对于 windows)并执行 "%~dp0\node.exe" "%~dp0\node_modules\angular-cli\bin\ng" %*

所以使用 npm start 你可以自己执行,其中 ng serve 仅适用于 angular-cli

另请参阅:

对于使用 CLI 的项目,您通常会使用 ng serve。在其他情况下,您可能想要使用 npm start。详细解释在这里:

服务

将服务于 'Angular CLI aware' 的项目,即使用 Angular CLI 创建的项目,特别是使用:

ng new app-name

因此,如果您使用 CLI 构建了一个项目,您可能想要使用 ng serve

npm 启动

这可以用于 不是 Angular CLI 感知的项目(或者它可以简单地用于 运行 'ng serve' 对于 Angular CLI 感知的项目)

正如其他答案所述,这是一个 npm 命令,它将 运行 来自 package.json 的具有标识符 'start' 的 npm 命令,但它不会'不必 运行 'ng serve'。在 package.json:

中可能有如下内容
   "scripts": {
     "build:watch": "tsc -p src/ -w",
     "serve": "lite-server -c=bs-config.json",
     "start": "concurrently \"npm run build:watch\" \"npm run serve\""
     ...
   },
   "devDependencies": {
     "concurrently": "^3.2.0",
     "lite-server": "^2.2.2",

在这种情况下,'npm start' 将导致以下命令为 运行:

concurrently "npm run build:watch" "npm run serve"

这将同时 运行 TypeScript 编译器(监视代码更改)和 运行 Node 精简服务器(使用 BrowserSync)

不止于此。执行的可执行文件不同

npm run start

将 运行 您的项目本地可执行文件位于 node_modules/.bin 中。

ng serve

将 运行 另一个全局可执行文件。

这意味着如果您克隆并安装一个使用 angular-cli 版本 5 创建的 Angular 项目并且您的全局 cli 版本是 7,那么您可能会遇到 ng build 问题。

如果你想 运行 angular 应用程序从另一台机器移植而不需要 ng 命令 然后编辑package.json如下

"scripts": {
    "ng": "ng",
    "start": "node node_modules/.bin/ng serve",
    "build": "node node_modules/.bin/ng build",
    "test": "node node_modules/.bin/ng test",
    "lint": "node node_modules/.bin/ng lint",
    "e2e": "node node_modules/.bin/ng e2e"
  }

最后 运行 常用 npm start 命令启动构建服务器。

最佳答案很好,简短而且切题,但我想把我的一分钱。

基本上npm startng serve可以互换使用在Angular 项目 只要您不希望命令执行其他操作 。让我详细说明一下。

例如,您可能希望在 package.json 启动脚本中配置您的代理,如下所示:"start": "ng serve --proxy-config proxy.config.json",

显然仅使用 ng serve 是不够的。

另一个例子是当你需要使用一些额外的选项而不是使用默认值时,比如定义临时端口:ng serve --port 4444

一些参数仅适用于 ng serve,其他参数适用于 npm start。请注意,port 选项对两者都适用,因此在这种情况下,它再次取决于您的口味。 :)