Writing npm modules in TypeScript

With TypeScript 4.x, TypeScript 3.x or TypeScript 2.x, the following steps describe what you have to do to create a library (npm package) with TypeScript:

  • Create your project as you normally would (with tests and everything)
  • Add declaration: true to tsconfig.json to generate typings.
  • Export the API through an index.ts
  • In the package.json, point to your generated typings. For example if your outDir is dist, then add "types": "dist/index.d.ts" to your package json.
  • In the package.json, point to your main entry file. For example if your outDir is dist and the main entry file is index.js, then add "main": "dist/index.js" to your package.json.
  • In the package.json, whitelist the files you'd like to ship to npm: files: ["/dist"]. An alternative approach is blacklisting with .npmignore, but it's harder to keep up to date.
  • Publish to npm with npm publish. Use semver specifications for updates (patch / bug fix npm version patch, non-breaking additions npm version minor, breaking api changes npm version major)

Since it got me a while to sift through all the outdated resources on this topic on the internet (like the one on this page...) I decided to wrap it up in how-to-write-a-typescript-library with an up-to-date working minimal example.


Here is a sample Node module written in TypeScript : https://github.com/basarat/ts-npm-module

Here is a sample TypeScript project that uses this sample module https://github.com/basarat/ts-npm-module-consume

Basically you need to :

  • compile with commonjs and declaration:true
  • generate a .d.ts file

And then

  • Have your ide read the generated .d.ts.

Atom-TypeScript just provides a nice workflow around this : https://github.com/TypeStrong/atom-typescript#packagejson-support