TypeScript: create library for NodeJS and browser
Use multiple tsconfig.json files to transpile your library for browser and server usage
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!
Photo: rawpixel.com