TypeScript: create library for NodeJS and browser

Use multiple tsconfig.json files to transpile your library for browser and server usage

Ronny Roeller
NEXT Engineering
2 min readSep 7, 2018

--

TypeScript allows to write code in modern JavaScript and then transpile it to a specific target platform. For example, you can code using ES6 features and still run it on a ES5 platform.

A special case are libraries that should be used in the browser and on the server. The following walk-through shows how to add an additional TypeScript build for browser usageto an existing TypeScript build for server usage.

First, create an additional configuration tsconfig.brower.json that instructs TypeScript to transpile for the browser into the directory /dist.browser:

Next, this additional build can be triggered from the package.json:

A build via npm install will already create the /dist.browser. Yet, the final build artifact published to your npm repository via npm publish will still miss the new folder. You can verify this also locally by running npm pack.

To include the missing folder, you need to declare all build folders in your package.json (this example assumes the transpile for server usage gets written to folder /dist):

Happy coding!

--

--

Ronny Roeller
NEXT Engineering

CTO at nextapp.co # Product discovery platform for high performing teams that bring their customers into every decision