npm start 是如何工作的?应该使用 npm run start 吗?(创建React应用程序)

5
在 Create React App 中,我们使用 npm start 启动应用程序,但在构建时,我们使用 npm run build。这应该是 npm run start,但是 npm start 是如何工作的?它是否是默认的 npm 脚本命令?

1
“npm run start” 是如此常见,以至于 npm 实现了一个快捷方式,使您无需键入“run”。 - Nicholas Tower
2个回答

5

有一组默认的内置npm脚本,可以在没有"run"关键字的情况下执行。这些是:

install, preinstall, preuninstall, postuninstall
prepublish, prepare, prepublishOnly, prepack, postpack, 
publish,preversion, version, postversion, 

pretest, test, posttest: Run by the npm test command.
prestop, stop, poststop: Run by the npm stop command.
prestart, start, poststart: Run by the npm start command.
prerestart, restart, postrestart: Run by the npm restart command. Note: npm restart will run the stop and start scripts if no restart script is provided.

有些脚本甚至可以在给定命令后自动运行(postinstall - 在“npm install”之后)。要完全理解这些脚本,请参考此处的文档。

除此之外,您还可以定义自定义脚本,以便运行:

  • 终端所支持的任何命令
  • npm 支持的任何命令

这些用户定义的自定义脚本应使用 "npm run ..." 来执行。

需要在这些脚本中运行的指令在 package.json 文件的 scripts 部分中定义。在下面显示的 package.json 中,“start”和“test”是内置的、npm 可识别的命令。“build”、“myinit”、“deletefolder”、“hellovnoitkumar” 是自定义的脚本,由用户自行定义。

此 package.json 支持的 npm 执行方式包括:

  • npm start (内置)
  • npm test (内置)
  • npm run build (自定义)
  • npm run myinit (自定义)
  • npm run deletefolder (自定义)
  • npm run hellovnoitkumar (自定义)

示例 package.json:

//npm start, npm test
//npm run build, npm run myinit, npm run deletefolder, npm run hellovnoitkumar
//*Note that you also can define what each built in npm command does (npm start, npm test).*
{
  "name": "my-webapp",
  "version": "0.1.0",
  "private": true,
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-scripts": "^2.1.5",
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "myinit" : "npm install && npm run build && npm start",
    "deletefolder": "rm -rf documents",
    "hellovnoitkumar": "echo "hello vnoit kumar""
  }
}

1

npm有许多内置命令,可以直接运行,如start、test、publish等。另一方面,用户定义的脚本需要使用"run"单词。您也可以使用带有"run"的内置脚本,它们是相当相似的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接