Jordi Jordi - 1 year ago 79
TypeScript Question

Generate an npm module from typescript files

I'm developing a npm module. This module is using Angular2 and TypeScript 2.

I'm facing up with a trouble related with how to generate this module.

I don't know which would be the steps I would need to follow in order to generate this npm module.

I've created a public repository on github.

What do I need to do in order to generate the npm module?

Answer Source

In your tsconfig.json you have set "declarations": true. It is supposed to be "declaration": true. And the exclude field needs to be outside compilerOptions. Also you are specifying that types need to be include from index.d.ts, When in fact there is no such file.

Now in order to generate the module follow the following steps.

  • Write the code for all the utilities you want to expose from your module. i.e all the entities that should be 'importable' from your module.

  • Once the above step is done make a file in src(Assuming src is your rootDir) called index.tsx or any other name of your choice. In this file export the entities you want to expose.

  • Next, in your package.json add "main": "<outDir>/index.js" and "typings": <outDir>/index.d.ts. Be sure to replace <outDir> with your output directory from tsconfig. The main field is used to tell the installing app where to import from when this module is referenced. For instance, If the installing app executes the following line of code

    import {abc} from 'swagger-client'

The main will tell node to look for abc inside the "<outDir>/index.js" file.
The typings field is just the typescript equivalent of main i.e. it tells node where to look for the types of abc in the above example.
Also notice the extensions of the files to be mentioned in the main and typings fields. They are not ts. By a rule of thumb you should not publish the .ts files to npm. Always commit the .ts files to github and publish the generated .js, .d.ts files to npm. The obvious reason for this is that by committing the generated files the module is usable in js projects as well as ts projects.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download