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

TypeScript提示找不到模块但实际存在,项目运行报错求助

问题:TypeScript项目运行时提示模块找不到

项目结构

├── dist
│   ├── hello.js
│   └── index.js
├── package-lock.json
├── package.json
├── src
│   ├── hello.ts
│   └── index.ts
└── tsconfig.json

各文件内容

hello.ts

export function sayHello() {
  console.log("Hello");
}

index.ts

import { sayHello } from "./hello";

sayHello();

tsconfig.json

{
  "compilerOptions": {
    "rootDirs": ["src"],
    "outDir": "dist",
    "lib": ["es2020"],
    "target": "es2020",
    "module": "esnext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "types": ["node"]
  }
}

package.json

{
  "name": "ts-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "compile": "tsc",
    "start": "npm run compile && node ./dist/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "type": "module",
  "devDependencies": {
    "@types/node": "^20.4.9",
    "typescript": "^5.1.6"
  }
}

错误信息

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '****/ts-test/dist/hello' imported from ****/ts-test/dist/index.js


解决方案

问题出在ES模块的扩展名要求:你在package.json里设置了"type": "module",启用了ES模块规范,但TypeScript编译后的index.js里的导入语句没有加.js后缀,而Node.js的ES模块必须指定完整的文件扩展名才能找到模块。

有两种解决方式:

方式一:修改TypeScript配置自动添加后缀

在tsconfig.json的compilerOptions中,将module和moduleResolution都改为nodenext,让TypeScript根据ES模块规则自动生成带.js后缀的导入语句:

{
  "compilerOptions": {
    "rootDirs": ["src"],
    "outDir": "dist",
    "lib": ["es2020"],
    "target": "es2020",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "esModuleInterop": true,
    "types": ["node"],
    "forceConsistentCasingInFileNames": true
  }
}

重新编译后,dist/index.js里的导入会变成import { sayHello } from "./hello.js";,Node.js就能正常识别模块了。

方式二:手动在TS文件中添加.js后缀

直接修改index.ts的导入语句,加上.js后缀(TypeScript会正确识别这个写法,不会报错):

import { sayHello } from "./hello.js";

编译后生成的JS文件会保留这个后缀,Node.js就能找到对应的模块。

另外建议把package.json里的main字段改成"dist/index.js",虽然这不是当前错误的原因,但能让配置更准确。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 19:15:59