You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

npx运行ts-node脚本提示Cannot find module 'tsconfig-paths/register'如何解决

问题根因

npx通过-p参数安装的依赖仅会将包的可执行文件路径加入系统PATH,不会自动将临时安装目录加入Node.js的模块解析路径。你给ts-node传-r tsconfig-paths/register参数时,Node.js按默认规则检索模块,找不到npx临时安装的tsconfig-paths包,因此抛出缺失模块的错误。

解决方案

方案1:使用ts-node内置paths支持(优先选择)

ts-node v10.7.0及以上版本已经原生支持tsconfig的paths配置,无需额外安装tsconfig-paths。你只需要在scripts/tsconfig.script.json中添加如下配置即可:

{
  "compilerOptions": {
    // 保留你原有配置
    "paths": {
      // 保留你原有路径映射规则
    }
  },
  "ts-node": {
    "experimentalResolver": true
  }
}

运行命令直接用你最初的版本即可:

npx -p typescript@latest -p ts-node@latest -p @types/node@latest ts-node -T --project scripts/tsconfig.script.json scripts/my-script.ts

方案2:显式指定tsconfig-paths的绝对路径

如果你使用的ts-node版本较低无法使用内置支持,可以在运行命令中动态获取tsconfig-paths/register的绝对路径传入:

npx -p typescript@latest -p ts-node@latest -p @types/node@latest -p tsconfig-paths@latest \
ts-node -T \
-r $(node -e "console.log(require.resolve('tsconfig-paths/register'))") \
--project scripts/tsconfig.script.json \
scripts/my-script.ts

方案3:临时追加NODE_PATH

你也可以手动将npx的临时依赖目录加入Node.js的模块检索路径:

NODE_PATH=$(npm root) npx -p typescript@latest -p ts-node@latest -p @types/node@latest -p tsconfig-paths@latest ts-node -T -r tsconfig-paths/register --project scripts/tsconfig.script.json scripts/my-script.ts

内容的提问来源于stack exchange,提问作者Michael Khaliavski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 05:24:04