【发布时间】:2021-06-11 00:50:28
【问题描述】:
我有一个小的 Typescript 库,我正在尝试使用正确的类型发布到 npmjs。但是,它似乎没有正确导出类型文件。
我在src/index.ts 文件中有一个简单的方法和来自src/typings/index.d.ts 的输入。 (部分函数名/参数重命名)
import { CoolData } from "./typings";
export const sampleExport = async (): Promise<CoolData[]> => {}
这是我的 tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"esModuleInterop": true,
"resolveJsonModule": true,
"lib": ["es6"],
"declaration": true,
"declarationMap": true,
"declarationDir": "dist",
"outDir": "dist",
"rootDir": "src",
"strict": true
},
"include": ["src"],
"exclude": ["node_modules", "**/*.spec.ts", "dist"]
}
和部分package.json
"main": "dist/index",
"types": "src/typings/index.d.ts",
"files": [
"dist",
"src/typings/index.d.ts"
],
当index.d.ts 在dist 文件夹中生成时,它的类型引用路径错误。
import { CoolData } from "./typings";
// Cannot find module './typings' or its corresponding type declarations.
即使是这样,我仍然可以发布和使用该库。但是,它为该方法返回 any 类型的缺点。
await sampleExport([]); // return type Promise<any>
尝试解决此问题已有一段时间,但无济于事。希望有人可以帮助我。谢谢。
编辑:
如果我允许 Typescript 自动生成我的输入,它会在 dist/index.d.ts 中生成这个错误
import { CoolData } from "./typings";
// Cannot find module './typings' or its corresponding type declarations.
export declare const sampleExport: () => Promise<CoolData[]>;
//# sourceMappingURL=index.d.ts.map
【问题讨论】:
-
尝试更改 package.json 文件的
types字段以引用“dist”文件夹。 Docs 明确表示“将 types 属性设置为指向捆绑的声明文件。” - 由于包在“dist”目录中,类型应该指向它。 -
@OlegValter我已经编辑了我的回复!请看一看。谢谢!
-
不确定我是否了解您的更新?您是否将
types字段切换为指向“dist”文件夹?你能展示一下你的输出文件夹结构是什么样的吗? -
@OlegValterjust 3 个文件。
dist/index.js、dist/index.d.ts和dist/index.d.ts.map。dist/index.d.ts会出现上述编辑中描述的错误。 -
我看到你自己想通了。刚刚注意到您使用
*.d.ts文件作为源文件,我不会这样做,因为您的代码库在打字稿中 - 您应该依赖*.d.ts文件发射来自 TS 文件。您可以将声明文件更改为真正的*.ts,并在构建步骤中删除不必要的发出 .js 文件。也就是说,直到今天我还不确定如何处理纯粹的环境 .ts 文件
标签: typescript npm typescript-typings