我遇到了解决打字稿中非相对模数的问题。并尝试baseUrl
,paths
等,但不起作用。...
tsconfig.json
{
"compilerOptions": {
"allowJs": true,
"baseUrl": ".",
"esModuleInterop": true,
"module": "commonjs",
"sourceMap": true,
"strict": true,
"target": "esnext",
"typeRoots": ["node_modules/@types"]
}
}
项目目录:
root
├─src
├── APIs
├── config
├── constants
├── middlewares
├── models
├── routes
├── services
- foo.ts
├── utils
└── app.ts
在 app.ts
中import foo from 'src/services/foo'
并运行ts-node src/app.ts
。
但是发生错误:
Cannot find module 'src/services/foo'
答案 0 :(得分:0)
最后,我添加了paths
选项来解决它。
tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"esModuleInterop": true,
"module": "commonjs",
"moduleResolution": "node",
"removeComments": true,
"sourceMap": true,
"target": "esnext",
"strict": true,
"noUnusedLocals": true,
"paths": {
"@/*": ["src/*"]
},
"typeRoots": ["./src/@types", "./node_modules/@types"]
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/node_modules/*", "**/*.spec.ts"]
}
在 app.ts 中:
import foo from '@/services/foo'