I’m working on an JavaScript NPM library package and trying to get typescript to generate a .d.ts
file from the jsdocs embedded in the file.
Let’s say I have the following three files:
index.js
, the main entry point into library:
export * from "./foo.js";
export * from "./bar.js";
foo.js
:
/** This is the foo function */
export function foo()
{
}
and bar.js
:
/** This is the bar function */
export function bar()
{
}
I then run tsc with config like so:
{
"include": [
"index.js",
],
"compilerOptions": {
"allowJs": true,
"declaration": true,
"emitDeclarationOnly": true,
"outFile": "index.d.ts",
"declarationMap": true,
}
}
and I get an index.ts.d
with this:
declare module "foo" {
/** This is the foo function */
export function foo(): void;
}
declare module "bar" {
/** This is the bar function */
export function bar(): void;
}
declare module "index" {
export * from "foo";
export * from "bar";
}
//# sourceMappingURL=index.d.ts.map
But this doesn’t work as expected with the intellisense in VSCode. For example, when adding imports, VS Code adds:
import { foo } from "foo";
instead of
import { foo } from "@myscope/mylib";
So what I’m hoping for is a way for tsc to generate something like this:
declare module "@myscope/mylib" {
/** This is the foo function */
export function foo(): void;
/** This is the bar function */
export function bar(): void;
}
//# sourceMappingURL=index.d.ts.map
What am I missing? Is there some way to get tsc to generate a .d.ts file where the entire library is considered a single module, with the scoped package name that I want?
2
Answers
First, you need to modify the configuration as follows:
This code will generate all type definitions into the
types
folder. At this point, if you only want your library to provide type hints, you can referencetypes/index.d.ts
.If your requirement is to generate a single
.d.ts
file containing the types of the entire library, I’m afraid to say thatTypeScript
itself does not support this capability. We need the support of a bundler, such asrollup
.First, install the necessary libraries:
Then, you can use this configuration file:
Next, run the command:
🎉 Now you have a single file containing the complete type:
I am not sure what is causing this issue for you. Maybe you can share the GitHub repo where you are facing this issue.
However, I have been using this Turborepo template to craft and publish my libraries. And it works perfectly fine for me.
Here is the tsconfig file – https://github.com/react18-tools/turborepo-template/blob/main/lib/tsconfig-build.json