简体   繁体   中英

How to expose TypeScript modules in NodeJS?

I have a library that I'm building in TypeScript. I'd like to include this library in both TypeScript and JavaScript Node projects. What is the general strategy to do this? Should I compile and have two versions or is there some other strategy I should be using?

I'd like to include this library in both TypeScript and JavaScript Node projects. What is the general strategy to do this?

Compile with the following to get the js output:

  • --module commonjs --outDir ./dist

This should make your project consumable by JS projects. To make it consumable by TS projects you need to generate a declaration file . This can be done using https://github.com/SitePen/dts-generator See usage for details : https://github.com/SitePen/dts-generator#usage

Note: There is discussion on removing the dts-generator dependency : https://github.com/Microsoft/TypeScript/issues/2338

In most cases I have seen you have a /dist/ folder where the compiled JavaScript is located.

Usually there is also a minified version like yourfilename.min.js - the rest is either outside or in a /src/ folder, so outside you have only the license/readme.md, package.json left and maybe the file for Grunt/Gulp (it is considered polite to - if you use a taskrunner - include a Grunt/Gulp file for compiling the typescript and minify the .js file afterwards, as far as I got it)

If you want to preserve the TypeScript advantages when using it in TypeScript projects, then you obviously have to expose a TypeScript version of the code so the TypeScript compiler can see the TypeScript declarations for your interface.

But, if you want people to be able to use your library in plain Javascript projects (that don't compile TypeScript into JS), then you have to offer a version that has a plain Javascript interface and where the code has already been compiled into plain JS.

So, if you want both of those advantages, then you have to offer two separate versions. The plain JS version can obviously just be a compiled version of the TypeScript (compiled into plain JS).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM