继承Command抽象类时出现Cannot find module编译错误
绝对路径导入抽象类编译报错,非继承场景却正常
问题描述
每次尝试继承抽象类Command并执行编译时,都会触发错误:
Error: Cannot find module 'src/classes/commandBase'
将导入路径改为相对路径../classes/commandBase后,编译完全正常。但VS Code的自动补全功能每次导入Command时,都会自动生成src/classes/commandBase这种绝对路径。
更奇怪的是,创建仅导入Command作为类型使用(不继承)的文件时,绝对路径导入可以正常工作,这种行为完全不符合预期。
项目结构
├────tsconfig.json └────src ├───classes │ └───commandBase.ts ├───commands │ └───ping.ts ├───handlers ├───listeners └───models
相关代码
commandBase.ts
abstract class Command { name: string; abstract execute(client: Client, message: Message, args: string[]): void; constructor(name: string) { this.name = name; } } export default Command;
ping.ts(报错的继承场景)
import Command from "src/classes/commandBase"; class Ping extends Command { constructor() { super("ping"); } async execute( client: Client, message: Message, args: string[] ): Promise<void> { // ... } } export default Ping;
foo.ts(正常的非继承场景)
import Command from "src/classes/commandBase"; const foo: Command = { name: "", execute: function (client: Client, message: Message, args: string[]): void { throw new Error("Function not implemented."); } }
tsconfig.json配置
{ "compilerOptions": { "target": "ESNext", "module": "CommonJS", "rootDir": "./src/", "outDir": "./dist/", "strict": true, "moduleResolution": "node", "importHelpers": true, "experimentalDecorators": true, "esModuleInterop": true, "skipLibCheck": true, "allowSyntheticDefaultImports": true, "resolveJsonModule": true, "forceConsistentCasingInFileNames": true, "removeComments": true, "typeRoots": ["node_modules/@types"], "sourceMap": true, "baseUrl": ".", "paths": {} }, "include": ["./**/**/*.ts"], "exclude": ["node_modules", "dist"] }
内容的提问来源于stack exchange,提问作者AidenDean
相关产品推荐
相关产品推荐

