我感到你的心痛,因为我花了大量时间调试 如何为现有 javascript 模块编写 typescript 定义文件上的各种错误,最终达到了我认为的最后一个障碍,当我遇到了同样的错误:
这个模块只能被 ECMAScript 导入/导出引用
打开“allowSyntheticDefaultImports”标志并引用其
默认导出
有问题的 javascript here:
module.exports = class AthenaExpress { ...more code.. }
tsconfig.json 用于编译/“工作版本”1:
{
"compilerOptions": {
"outDir": "dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es6",
"jsx": "react"
},
"baseUrl": "./src",
"include": [
"**/*"
],
"exclude": [
"node_modules"
]
}
d.ts 文件的“工作版本”与一些导入差异2:
declare module 'athena-express' {
import * as aws from "aws-sdk";
interface ConnectionConfigInterface {
aws: typeof aws,
s3: string,
getStats: boolean
}
interface QueryResultsInterface {
Items: any[],
DataScannedInMB: number,
QueryCostInUSD: number,
EngineExecutionTimeInMillis: number,
Count: number,
}
interface QueryInterface {
sql: string,
db: string,
}
type QueryResult = QueryResultsInterface
interface AthenaExpressInterface {
new: (config: ConnectionConfigInterface) => any,
query: (query: QueryInterface) => QueryResult,
}
class AthenaExpress {
new: (config: ConnectionConfigInterface) => any;
constructor(config: ConnectionConfigInterface);
query: (query: QueryInterface) => QueryResult;
}
}
收到相同错误的d.ts 文件的版本,即使启用了esModuleInterop,我也摆弄module 和target 无济于事。与import语句的区别3:
import * as aws from "aws-sdk";
interface ConnectionConfigInterface {
aws: typeof aws,
s3: string,
getStats: boolean
}
interface QueryResultsInterface {
Items: any[],
DataScannedInMB: number,
QueryCostInUSD: number,
EngineExecutionTimeInMillis: number,
Count: number,
}
interface QueryInterface {
sql: string,
db: string,
}
type QueryResult = QueryResultsInterface
interface AthenaExpressInterface {
new: (config: ConnectionConfigInterface) => any,
query: (query: QueryInterface) => QueryResult,
}
declare class AthenaExpress {
new: (config: ConnectionConfigInterface) => any;
constructor(config: ConnectionConfigInterface);
query: (query: QueryInterface) => QueryResult;
}
export = AthenaExpress
注意事项:
定义文件位置和我试图使用该定义的文件:
tree src/backend/js
src/backend/js
├── athena-express.d.ts
└── helloworld.ts
- “工作版”意思是
tsc 似乎编译没有抱怨
- 在 helloworld.ts
import {AthenaExpress} from "athena-express";
- 在 helloworld.ts
import * as AthenaExpress from "./athena-express";