TypeScript: create library for NodeJS and browser

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

Ronny Roeller
Sep 7, 2018 · 2 min read

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:

{
"compilerOptions": {
"baseUrl": ".",
"outDir": "./dist.browser",
"target": "es5",
"module": "es2015",
"moduleResolution": "node",
"lib": ["es2016", "dom", "es5"]
},
"include": [
"./src/**/*"
]
}

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

{
"scripts": {
"build": "tsc && tsc -p tsconfig.browser.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):

{
"files": [
"dist",
"dist.browser"
},

...
}

Happy coding!


NEXT Engineering

Tech lessons learned while making innovation smart, simple and sticky.

Ronny Roeller

Written by

CTO at @Next. Building agile SaaS platform to make innovation smart, simple and sticky. @stanforddschool @INSEAD

NEXT Engineering

Tech lessons learned while making innovation smart, simple and sticky.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade