运行npx npm-run-all抛出"Cannot find module"错误的原因排查
Angular自定义脚本运行失败问题解决
问题描述
应用最初基于Node.js 16.10.0、npm 6.23.2、Angular CLI 14.2.10创建,升级到Node.js 16.13.0、npm 8.1.0、Angular CLI 15.0.2后,ng serve和ng build可正常执行,但运行npm run test:precheckin时出现模块找不到错误,提示无法找到test和build:int模块。
错误日志关键片段:
Starting: test node:internal/modules/cjs/loader:936 throw err; ^ Error: Cannot find module 'D:\angular migration POC\Angular14App\AngularApp\test'
Starting: build:int node:internal/modules/cjs/loader:936 throw err; ^ Error: Cannot find module 'D:\angular migration POC\Angular14App\AngularApp\build:int'
问题原因
test:precheckin脚本使用npm-run-all时语法错误,npm-run-all默认将参数视为可执行文件/Node模块,而非npm脚本。加上build:int这类带冒号的脚本名称,进一步触发了路径解析错误,导致Node尝试在项目目录下查找名为test和build:int的文件,自然找不到。
解决方法
修改package.json中的test:precheckin脚本,明确指定运行npm脚本,有两种常用方案:
方案1:使用run-s(串行执行脚本,npm-run-all的简写命令)
将脚本修改为:
"test:precheckin": "npx run-s test \"build:int\""
run-s是npm-run-all --series的简写,专门用于串行执行npm脚本,引号包裹带冒号的脚本名避免解析错误。
方案2:显式调用npm run
如果偏好更清晰的写法,也可以直接指定每个脚本通过npm run执行:
"test:precheckin": "npx npm-run-all \"npm run test\" \"npm run build:int\""
额外检查
如果修改后仍有问题,可尝试:
- 删除
node_modules和package-lock.json,重新执行npm install确保依赖一致 - 确认
npm-run-all版本兼容当前npm版本(使用npx npm-run-all --version查看)
内容的提问来源于stack exchange,提问作者GokuSS3
相关产品推荐
相关产品推荐

