Writing npm modules in TypeScript

前端 未结 7 503
醉话见心
醉话见心 2020-11-30 16:58

I am working on my first npm module. I briefly worked with TypeScript before and a big problem was that for many modules there were no definition files available. So I thoug

7条回答
  •  佛祖请我去吃肉
    2020-11-30 17:50

    With 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.
    • Create an .npmignore to ignore unnecessary files (e.g. the source).
    • 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.

提交回复
热议问题