4

i want to write a npm module in TypeScript. Can someone recommend me a best practice guide how to get started?

My Questions are:

  • Node.js don't support TypeScript out of the box, right? So how is the recommended way to publish a npm module? Make 2 Folders /ts /js and reference in the package.json to js/index.js as entry point. Or use some kind of a runtime transpiler and run the TypeScript file directly? Or is it not recommended anyway to publish any TypeScript Code in a npm module and just compile it down to normal Javascript and provide the TypeScript source in a Git repository?

  • What is the recommended way for Typing Support? I saw i can reference in my package.json to the Typing Files. Can they be online, should i provide them with the npm module or should ts and dtd files not be published at all? Install them with typings and provide the typings.json as well?

  • If i want to provide typing support for my code how is the recommended way to do this? even my modules are very small and simple (do one thing and do it right) it could be useful to provide some information and autocompletion support. I'm still new to TypeScript so not sure whats the best way to do this. I would guess writing a Interface and provide it with my npm module. Should these files later be uploaded to the DefinitelyTyped directory or does this only for larger libraries sense?

I would love to here how to do it correctly with the current TypeScript and Node Version since lot of the informations i found are outdated referring to stuff like autodts, tsd and so on.

Im very glad if someone can help me. As soon i know how this is done the right way i will make a documentation and provide these information for others on Github.

Cheers

bin2hex
  • 345
  • 3
  • 15

1 Answers1

5

To your first question: Yes, you have to transpile the typescript code before you can publish you npm package but you can do this very easily by making sure you have this in your package.json:

  "scripts": {
    "prepublish": "tsc",
  }

Best practice for structering the files is to use e.g. a src directory for your ts files and then the root level or another directory (e.g. dist) for the js files. You can set this up by defining the "outDir" in your tsconfig.json:

"compilerOptions": {
    [...]
    "outDir": "dist"
}

Also the links in the accepted answer here helped me with similar questions: Writing NPM modules in Typescript

As for your question about the typing in the npm package: For providing the typing in the current typescript version you don't need to change anything in your package.json. You can just add a file called index.d.ts to the root level of your package. If somebody uses your module typescript will automatically find the typing there.

Community
  • 1
  • 1
June
  • 385
  • 5
  • 14