重写 npm 脚本以与 windows cmd 兼容

Rewrite npm script to be compatible with windows cmd

我正在尝试 运行 为 linux 命令行编写的教程中的脚本,但我 运行 在将其转换为兼容的内容时遇到错误windows。这是文章中的行:

"build": "cd react-spa && yarn build && cd .. && cp -R react-spa/build/ public/ && mv public/index.html public/app.html"

这就是我所拥有的

cd client && yarn build && cd .. && xcopy client/build/ public/ /E && ren public/index.html app.html

这是我在终端中得到的错误信息

Invalid number of parameters
npm ERR! code ELIFECYCLE
npm ERR! errno 4
npm ERR! api@0.0.0 build: `cd client && yarn build && cd .. && xcopy client/build/ public/ /E && ren public/index.html app.html`
npm ERR! Exit status 4
npm ERR!
npm ERR! Failed at the api@0.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\user\AppData\Roaming\npm-cache\_logs20-05-01T05_29_54_552Z-debug.log

我做错了什么?

package.json 中重新定义您的 build 脚本,如下所示:

"build": "cd react-spa && yarn build && cd .. && xcopy /e/h/y/q \"react-spa/build\" \"public\\" > nul 2>&1 && del \"public\app.html\" > nul 2>&1 && ren \"public\index.html\" \"app.html\""

注:上述npm脚本假设你是运行宁Windows而默认shell是npm 脚本使用的是 cmd.exe.


解释:

进行了以下更改以匹配与原始 npm build 脚本(即使用 *nix 命令编写的脚本)相同的行为:

  1. 以下cp命令:

    cp -R react-spa/build/ public/
    

    已改进为使用 xcopy 命令,如下所示:

    xcopy /e/h/y/q \"react-spa/build\" \"public\\" > nul 2>&1 
    

    选项:

    • /e - 复制文件夹和子文件夹,包括空文件夹。
    • /h - 复制隐藏和系统文件和文件夹。
    • /y - 取消确认覆盖文件的提示。
    • /q - 复制时不显示文件名。

    备注:

    • 每个路径名都包含在 JSON 转义双引号中,即 \"...\"

    • public\部分有一个尾部反斜杠(\),已被JSON转义(\),以通知xcopy 目标是一个目录。这也确保创建 public 目录(如果它不存在)。

    • > nul 2>&1 部分禁止显示复制了多少文件的确认日志。

  2. 以下mv命令:

    mv public/index.html public/app.html
    

    已经改进为使用两个 del and ren 命令,如下所示:

    del \"public\app.html\" > nul 2>&1 && ren \"public\index.html\" \"app.html\"
    

    备注:

    • 我们首先尝试删除app.html文件,以确保后续的ren命令可以将index.html文件重命名为app.html而不会产生任何冲突由于已存在重复文件。

      我们使用 > nul 2>&1 进行重定向,以确保我们在无法找到 app.html 文件时阻止任何日志,即在构建的第一个 运行 期间找不到该文件时脚本.

    • 每个路径名都包含在 JSON 转义双引号中,即 \"...\".
    • public\index.html 部分,在 delren 命令中,使用反斜杠分隔符 (\),已被 JSON 转义 ( \)。而不是正斜杠 (/).