为什么“DEBUG=foo node index.js”在“package.json”的“scripts”部分失败

2023-11-30

我使用的是 Windows 10,但我正在使用git bash。当运行时从git bash下列:

DEBUG=foo node index.js

它工作正常并设置环境变量DEBUG。但如果我把它放入scripts的部分package.json:

  "scripts": {
    "start": "DEBUG=foo node index.js"
  },

并运行以下命令git bash我收到以下错误:

$ npm start

> [email protected] start C:\Users\maksym.koretskyi\Desktop\nodejs
> DEBUG=foo node index.js

'DEBUG' is not recognized as an internal or external command,
operable program or batch file.

为什么会有这样的行为?


看起来你是在 Windows 上运行它。

假设你有 Bash 正如你所说的那样工作,我会制作一个脚本:

#!/bin/bash
DEBUG=foo node index.js

称为例如run-debug并使用:

"scripts": {
    "start": "bash run-debug"
},

in package.json以确保DEBUG=foo node index.jscommand 由 Bash 解释,而不是 command.com 或 Windows 中任何调用的 shell。看问题 #6543:npm 脚本 shell 选择.

如果您希望它甚至可以在没有 Bash 的系统上运行,为了获得最大的跨平台兼容性,最好使用 Node 脚本而不是 shell 脚本:

"scripts": {
    "start": "node run-debug.js"
},

在这种情况下run-debug.js可能包含类似以下内容:

let env = Object.create(process.env);
env.DEBUG = 'foo';
spawn('node', ['app.js'], {env});

也可以看看:

  • cygwin/windows下的npm脚本:命令语法不正确
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么“DEBUG=foo node index.js”在“package.json”的“scripts”部分失败 的相关文章

随机推荐