为何Shell中npx <cmd>与./node_modules/bin/<cmd>执行结果不同?
npx与直接调用node_modules二进制文件的glob匹配差异问题
在macOS 14.0(使用bash 5.2.15)环境下,直接在终端执行npx命令调用mochify时,和直接运行./node_modules/.bin/mochify的结果不一致:
- 执行这条npx命令仅运行1个测试文件(44个用例通过,2个待处理):
npx mochify -R dot --no-detect-globals --recursive --grep WebWorker --invert 'test/**/*-test.js' - 直接调用二进制文件则运行全部测试文件(1492个用例通过,13个待处理):
./node_modules/.bin/mochify -R dot --no-detect-globals --recursive --grep WebWorker --invert 'test/**/*-test.js'
但把这两条命令写入Shell脚本执行时,二者的表现完全一致。
问题原因
npx在转发命令参数时,会通过额外的Shell进程处理参数传递,导致原本用单引号包裹的test/**/*-test.js glob模式被bash提前展开为单层路径匹配(仅匹配test目录下直接的*-test.js文件)。而直接调用二进制文件时,单引号能有效阻止Shell展开glob,让mochify自身处理递归路径的匹配逻辑。
解决方法
- 转义glob通配符:对
**进行转义,避免Shell提前展开,命令改为:npx mochify -R dot --no-detect-globals --recursive --grep WebWorker --invert 'test/\*\*/\*-test.js' - 使用双引号包裹glob:确保bash的
globstar选项开启(bash 4+默认开启,可通过shopt -s globstar手动开启),命令改为:npx mochify -R dot --no-detect-globals --recursive --grep WebWorker --invert "test/**/*-test.js" - 用
--分隔npx参数:明确将后续所有参数直接传递给mochify,避免npx的参数解析干扰:npx -- mochify -R dot --no-detect-globals --recursive --grep WebWorker --invert 'test/**/*-test.js'
内容的提问来源于stack exchange,提问作者oligofren
相关产品推荐
相关产品推荐

