I've been moving a few utilities that I use in multiple projects to npm libraries. But I needed an easy, reliable way to generate TypeScript declarations, since I primarily use TypeScript.
Open your project and ensure you have a
package.json-
Install the
typescriptlibrary as a development dependency
- With
pnpm:pnpm i -D typescript - With
npm:npm i -D typescript - With
yarn:yarn add typescript -D
- With
-
Add JSDoc tags to your functions, variables, classes, etc.
For example, here's a snippet from one of my utilities:
/** * Apply classes that result in a true condition * @param {string[]} classes * @returns A list of classes * * @example * classNames("block truncate", selected ? "font-medium" : "font-normal") */ export const classNames = (...classes) => { return classes.filter(Boolean).join(" "); }; -
Add the
preparescript (or whichever one you want to use) to thescriptsobject inpackage.jsonFor example, mine looks like this:
"scripts": { "prepare": "tsc --declaration --emitDeclarationOnly --allowJs index.js" },This command runs
tsc, the TypeScript compiler, and tells it to only generate.d.tsfiles (declaration files). Be sure to replaceindex.jswith your JavaScript files.The
preparescript runs before a npm package is packed (typically withnpm publishornpm pack, or the equivalents with other package managers). -
Run your npm script
- With
pnpm:pnpm prepareorpnpm run prepare - With
npm:npm run prepare - With
yarn:yarn run prepare
- With
Using the classNames function above, the TypeScript compiler generated the following declaration:
export function classNames(...classes: string[]): string;
If you have any questions, send a tweet my way. I hope that this guide comes in handy for you, thanks for reading!
Top comments (0)