TypeScript中export default在CommonJS环境失效,ts-node运行报错
解决ts-node下TypeScript默认导出导入报错问题
错误原因
你在app.ts里导入时写了./helloWorld.js,但ts-node是直接运行TypeScript源文件,不会自动查找编译后的JS文件,所以这个路径找不到对应的模块。
修复步骤
- 修改app.ts的导入路径,去掉
.js后缀:
import helloWorld from "./helloWorld"; helloWorld();
- 确保tsconfig.json配置正确(没有的话新建一个),保证模块解析正常:
{ "compilerOptions": { "module": "CommonJS", "moduleResolution": "node", "target": "ES6", "esModuleInterop": true } }
- 用ts-node直接运行app.ts:
ts-node app.ts
执行后就能正常输出Hello world!了。
内容的提问来源于stack exchange,提问作者Aletropy
相关产品推荐
相关产品推荐

