当您将 `npm 运行` 调用到 运行 一个 NPM 脚本时,幕后会发生什么?

What happens under the hood when you call `npm run` to run a NPM script?

我想进一步了解 NPM 脚本的工作原理。

例如:

package.json

"scripts": {
  "build": "set NODE_ENV=production&& webpack --config webpack.config.js",
}

当我执行 npm run build:

会发生什么?我知道 Node 进程将在某处启动并且 webpack 二进制文件将被调用,对吗?但在那之前的步骤是什么?这是否取决于我使用的是 Windows、Linux、PowerShell 还是 Git bash?该过程与正在使用的 OS 和 CMD/CLI 有何关系?

npm 源代码将整个 run-script 功能分离到它自己的模块和存储库中,因此您可以 review the source code if the documentation 不回答您的问题。

说到你的问题:

I know a Node process will be initiated somewhere and webpack binary file will be called, right?

webpack 可执行文件将是 运行。由于 webpack 是一个 Node.js 脚本,它将是 运行 和 node.

但是,如果您的“构建”值包含 shell/CLI 个命令,那么这些命令将是 运行。 Node.js不一定被调用。

But what are the steps before that?

“之前的步骤”包括也可能定义的某些生命周期脚本。特别是,如果有“prebuild”脚本,它会在“build”脚本之前运行。

Does that depend whether I'm on Windows, Linux, PowerShell or Git bash? How does that process relate to the OS and the CMD/CLI that is being used?

npm(和 node)努力使 Windows 和 Linux 的体验具有可比性。差异肯定会发生,但没有更多细节,我不确定我是否想推测除此之外您可能感兴趣的细节。

Powershell 和 GitBash:同样,npm 将努力消除差异,但我确信它们会出现。需要注意的一件事是您的 PATH(和其他环境变量)可能设置不同,这可能会影响行为。 (如果您安装了多个版本,它可能会特别影响执行哪个版本的 node。)

我不是 Windows 专家,但我见过很多 npm 假设类 UNIX 环境的脚本。因此,如果给定选择并且其他所有条件都相同(从来没有),bash-like 环境可能会更平滑一些。

我正在寻找的答案是这样的:

当您调用 npm run 时,npm 将启动 shell 到 运行 那些指令。

npm 将使用哪个 shell 在您的 npm 设置中定义。

您可以通过 运行ning 查看您的 npm 配置:

>>> npm config ls

在上面的示例中,npm 将 运行 上的脚本 git-bash

您可以通过调用更改 npm shell:

npm config set script-shell "C:\Program Files\git\bin\bash.exe"