执行npx tsc && node dist报错:无法找到模块'./dist',求配置排查
问题解决:Error: Cannot find module './dist'
核心原因分析
node dist命令用法错误:Node.js 需要指定具体的执行文件而非目录,直接输入node dist时,Node 会尝试查找dist/index.js,但如果编译后的文件结构不符合预期,就会触发找不到模块的错误。- tsconfig.json 配置问题:
rootDir设置为./会导致编译时保留原目录结构,比如src/index.ts会被编译到dist/src/index.js而非dist/index.js,这就导致node dist找不到入口文件。
具体修复步骤
1. 修正 tsconfig.json 的 rootDir 配置
将rootDir从./改为./src,确保编译后的文件直接输出到dist根目录:
{ "compilerOptions": { "composite": true, "target": "esnext", "module": "commonjs", // 改为commonjs适配Node.js默认模块系统,或后续在package.json加"type": "module" "rootDir": "./src", // 修正此处 "strict": true, "skipLibCheck": true, "outDir": "dist", "sourceMap": true, "declaration": true }, "include": [ "src" ] }
2. 正确执行编译与运行命令
- 重新编译:
npx tsc - 运行编译后的入口文件(假设入口是
index.js):node dist/index.js
3. 可选:优化命令(通过 package.json scripts)
在package.json中添加脚本,简化操作:
{ "scripts": { "build": "npx tsc", "start": "node dist/index.js", "dev": "npx tsc && node dist/index.js" } }
之后可以直接运行npm run dev完成编译+运行。
额外注意点
如果坚持使用module: "esnext",需要在package.json中添加"type": "module",否则 Node.js 会以 CommonJS 模式加载模块,导致 ES 模块语法报错。
内容的提问来源于stack exchange,提问作者tunamayo
相关产品推荐
相关产品推荐

