创build一个自定义的打字文件
我刚刚创build了一个名为“Foo”的已发布npm
包。 我正在尝试在打字稿项目中使用它,但是没有关于如何声明模块的定制打印的教程,我很清楚。 这是npm包的关键部分:
news.ts
import { tdsRequest } from "../common/request"; function articles(uri) { return tdsRequest({ method: "GET" }, uri).then(returnData => console.log(returnData, "return data")); } export { articles, };
main.ts
(主要出口)
import * as news from "./services/news"; export default { news };
在使用npm
包的打字稿项目中: import { news } from "Foo";
和types文件( Foo.d.ts
)中,我做了:
declare module "Foo" { export { news: Object, }; }
我得到以下错误: cannot find module news
, Cannot export 'Object'. Only local declarations can be exported from a module.
Cannot export 'Object'. Only local declarations can be exported from a module.
您正在混合默认和命名导出。
你可以做默认的导出风格 –
main.ts:
import * as news from "./services/news"; export default { news };
项目导入:
import foo from "Foo"; const {news} = foo;
foo.d.ts:
declare module "Foo" { export default { news: Object, }; }
或者你可以做命名的出口 :
main.ts:
import * as news from "./services/news"; export { news };
项目导入:
import {news} from "Foo";
foo.d.ts:
declare module "Foo" { export const news: Object; }
但更重要的是,你应该在你的npm库中的tsconfig.json
中添加declaration: true
到你的compilerOptions
。
这将为您生成d.ts
文件,并为您节省大量的工作。 然后,您需要在package.json
添加一个名为types
的main.d.ts
,它将指向将为您生成的main.d.ts
文件。 这将允许任何使用你的库+ typescript的项目自动使用生成的types。