Windows下PowerShell无法识别本地安装的NPM bin模块求助
本地NPM CLI命令在Windows PowerShell中无法执行的问题
我在Windows上创建了一个可作为可安装NPM CLI命令的本地项目,但测试时不符合预期:
- 拉取项目后,进入
module-b目录执行npm i安装module-a,node_modules/.bin目录下生成了hello-world、hello-world.cmd和hello-world.ps1文件 - 在PowerShell中直接执行
hello-world时,报错:
hello-world : The term 'hello-world' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
相关配置
Module A 的 package.json
{ "name": "module-a", "version": "1.0.0", "description": "module-a", "main": "main.js", "bin": { "hello-world": "main.js" }, "author": { "name": "" } }
Module A 的 main.js
#!/usr/bin/env node console.log('hello world!');
Module B 的 package.json
{ "name": "module-b", "version": "1.0.0", "description": "module-b", "main": "main.js", "author": { "name": "" }, "dependencies": { "module-a": "file:../module-A" } }
Node版本:20.0.0,NPM版本:9.6.4
解决方法
- 直接使用相对路径执行:PowerShell默认不会把当前项目的
node_modules/.bin加入系统PATH,直接指定路径运行即可:.\node_modules\.bin\hello-world - 用npx自动查找命令:npx会自动扫描项目的
node_modules/.bin目录,直接执行:npx hello-world - 临时添加路径到当前会话的PATH:在PowerShell中执行以下命令,将
node_modules/.bin加入当前会话环境变量,之后就能直接输入hello-world运行:$env:PATH += ";.\node_modules\.bin" - 通过npm scripts执行:在Module B的
package.json中添加scripts字段:
然后执行:{ // ...其他配置 "scripts": { "hello": "hello-world" } }npm run hello
内容的提问来源于stack exchange,提问作者Steffen Cole Blake
相关产品推荐
相关产品推荐

