运行 npm 脚本中的批处理文件

run batch file in npm script

是否有可能以及如何在 npm 命令中 运行 批处理脚本?

我有一个 angular 项目,在 package.json 文件的 scripts 部分下,我想为 运行 批处理脚本定义一个 npm 命令。我知道我可以 运行 shell 带有关键字 bash 的脚本,例如

"start": "cd mydir && bash ./myscript"

然后我可以在我的项目目录下运行 npm start,这将改变目录并执行myscript.sh脚本。 npm 中 运行 批处理脚本的等效关键字是什么?

这里是新手。抱歉,如果这是一个重复的问题;也许我没有搜索正确的术语,但我看不到找到这个问题的答案。

为了帮助提供此答案的上下文,假设我们有两个名为 say-hello.batsay-hello-cmd 的批处理文件。两个批处理文件都具有相同的简单设计内容,如下所示:

echo Hello World

当通过 npm-scripts 调用两个批处理文件中的任何一个时,我们希望控制台记录:

Hello World

项目目录结构:

现在,假设我们的项目目录结构如下:

.
├── a
│   └── b
│       ├── say-hello.bat
│       └── say-hello.cmd
├── package.json
├── say-hello.bat
├── say-hello.cmd
└── ...

如您所见,我们有:

  • say-hello.batsay-hello.cmd存放在项目根目录下。他们与 package.json.
  • 处于同一级别
  • 我们还有say-hello.batsay-hello.cmd存储在项目目录的子目录中,它们的路径是:a/b/

npm-scripts

为了能够通过 npm 调用这些批处理文件,package.jsonscripts 部分应该定义如下:

{
  ...
  "scripts": {
    "bat": "say-hello.bat",
    "cmd": "say-hello.cmd",
    "bat-in-sub-dir": "cd a/b/ && say-hello.bat",
    "cmd-in-sub-dir": "cd a/b/ && say-hello.cmd"
  },
  ...
}

如果您现在 cd 到您的项目目录并 运行 以下任何命令:

  • npm run bat
  • npm run cmd
  • npm run bat-in-sub-dir
  • npm run cmd-in-sub-dir

批处理文件将为 运行,您将成功地看到 Hello World 字样记录到控制台。

备注

上述示例之间的显着区别是:

  • 当批处理文件存储在项目目录的根目录中时,您只需在脚本中提供批处理文件的名称。例如

    "bat": "say-hello.bat"
    
  • 当批处理文件存储在项目目录的子目录中时(例如a/b/),您必须首先cd到该文件夹​​,然后提供名称批处理文件到 运行。例如

    "bat-in-sub-dir": "cd a/b/ && say-hello.bat"
    

可以直接使用

"start": "mydir\myscript.bat"