Reputation: 4187
I just created a published npm
package for the first time, called "Foo". I am trying to consume it in a typescript project, but none of the tutorials about how to declare modules with custom typings, are clear to me. Here are the key parts of the npm package:
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
(main export)
import * as news from "./services/news";
export default {
news
};
in the typescript project that's consuming the npm
package:
import { news } from "Foo";
and in the typings file ( Foo.d.ts
) I did:
declare module "Foo" {
export {
news: Object,
};
}
I get the following errors: cannot find module news
and Cannot export 'Object'. Only local declarations can be exported from a module.
Upvotes: 3
Views: 1603
Reputation: 1717
You are mixing default and named exports.
You can do default export style -
main.ts:
import * as news from "./services/news";
export default {
news
};
ts project import:
import foo from "Foo";
const {news} = foo;
foo.d.ts:
declare module "Foo" {
export default {
news: Object,
};
}
Or you can do named exports:
main.ts:
import * as news from "./services/news";
export {
news
};
ts project import:
import {news} from "Foo";
foo.d.ts:
declare module "Foo" {
export const news: Object;
}
But more importantly, you should add declaration: true
to your compilerOptions
in tsconfig.json
in your npm library.
This will generate the d.ts
file for you and will save you lots of work. Then, you need to add in package.json
a filed called types
that will point to the main.d.ts
file that will be generated for you. This will allow any project using your library + typescript to use the generated types automatically.
Upvotes: 2