Ruifeng Ma
Ruifeng Ma

Reputation: 2787

Best practice in organizing NPM module exports in a typescript library project?

I am writing a library package in Typescript to be published to the npm registry such that it can be used by various other projects.

I have followed the publishing doc to ensure that the --declaration option is true for tsc such that type definitions are exported as well in *.d.ts files.

The question I have is right now such exports are scattered in various folders and the consumers of my package are importing them like below.

import { FooType } from 'my-test-pacakge/dist/src/foo/types';
import { BarInterface } from 'my-test-package/dist/src/foo/bar';

I am wondering whether this is acceptable as it looks messy. Should I write my own declaration file to organize them in a cleaner manner?

There are existing answers to similar questions suggesting exporting the API through a general index.ts file. That sounds pretty legitimate to me but I am just wondering whether importing from the dist folder directly is considered bad practice?

Upvotes: 2

Views: 1389

Answers (1)

Evert
Evert

Reputation: 99533

Most packages will prefer to export from 1 export point, so that the user of your libraries does not need to know anything about the directory structure of your package.

import { FooType, BarInterface } from 'my-test-package'.

A bonus benefit is that you can restructure the internals of your package without affecting the end-user, and it clearly delineates what the items are that you intend to be used by users of your package, and which are internal to your package.

So yes, I would agree that this is a best practice.

There are some packages that have additional namespacing, the mysql2 package comes to mind that has two major exports:

import { Connection } from 'mysql2';
import { Connection } from 'mysql2/promise';

But note that there's nothing like dist in here. dist is not meaningful to the end-user.

Upvotes: 8

Related Questions