[英]Typescript local file class 'Cannot find module'
Having the below folder structure具有以下文件夹结构
- api
- routes
- meeting.ts
- models
- DynamoService.ts
tsconfig.json tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"outDir": ".build",
"strict": true,
"baseUrl": "./",
"typeRoots": ["node_modules/@types"],
"types": ["node"],
"esModuleInterop": true,
"preserveConstEnums": true,
"sourceMap": true,
"allowJs": true,
"moduleResolution": "node",
"rootDir": "./",
"removeComments": true,
"noEmitOnError": true,
"noUnusedLocals": true,
"noImplicitReturns": true
},
"exclude": ["node_modules"]
}
DynamoService.ts DynamoService.ts
export class DynamoService {
...
}
meeting.ts会议.ts
import { DynamoService } from 'models/DynamoService'
const dynamoService = new DynamoService()
// other Express stuff...
When testing this I receive the below runtime error测试时,我收到以下运行时错误
Error: Cannot find module 'models/DynamoService'
Before trying to move the functionality into a class module having some DynamoDB helper methods in meeting.ts
was working just fine.在尝试将功能移动到 class 模块之前,在
meeting.ts
中具有一些 DynamoDB 帮助器方法工作得很好。 Visual Studio Code doesn't complain about anything, no compile errors. Visual Studio Code 不会抱怨任何事情,也不会出现编译错误。
That should be a simple task but I seem to have trouble!这应该是一个简单的任务,但我似乎有麻烦!
There are two approaches to solve this problem.有两种方法可以解决这个问题。
You could simply change the import line like this:您可以像这样简单地更改导入行:
import { DynamoService } from '../../models/DynamoService'
Another convenient way is to leverage this nice TypeScript feature by configuring paths
in tsconfig.json
:另一种方便的方法是通过在
tsconfig.json
中配置paths
来利用这个漂亮的 TypeScript 功能:
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"models/*": ["models/*"]
},
}
See more in https://www.typescriptlang.org/tsconfig#paths or https://medium.com/slackernoon/use-typescript-aliases-to-clean-up-your-import-statements-7210b7ec2af1 .在https://www.typescriptlang.org/tsconfig#paths或https://medium.com/slackernoon/use-typescript-aliases-to-clean-up-your-import-statements-7210b7ec2af1中查看更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.