skip to content
Risqi Romadhoni

Building a TypeScript Library in a Monorepo with PNPM and Turborepo

/ 2 min read

📌 Introduction

Building a TypeScript library in a monorepo offers several advantages, including better code sharing, streamlined dependency management, and easier maintainability. This guide will walk you through setting up a monorepo structure for a TypeScript library using modern tools like pnpm, Turborepo, and TypeScript.

🛠️ Setting Up the Monorepo

Initialize the Monorepo

We will use pnpm as our package manager since it natively supports workspaces and provides better performance compared to npm and yarn.

Terminal window
mkdir ts-monorepo && cd ts-monorepo
pnpm init

Enable workspaces in pnpm by adding the following to package.json:

1
{
2
"private": true,
3
"workspaces": ["packages/*"]
4
}

Install Turborepo for Task Orchestration

Turborepo helps manage build processes and dependencies efficiently.

Terminal window
pnpm add -D turbo

Create a turbo.json configuration file:

1
{
2
"$schema": "https://turborepo.org/schema.json",
3
"pipeline": {
4
"build": {
5
"dependsOn": ["^build"],
6
"outputs": ["dist/**"]
7
},
8
"lint": {},
9
"test": {}
10
}
11
}

🏗️ Creating the TypeScript Library

Set Up the Package

Create a new package for the library:

Terminal window
mkdir -p packages/my-library && cd packages/my-library
pnpm init

Install TypeScript and necessary dependencies:

Terminal window
pnpm add -D typescript tsup eslint @types/node

Create a tsconfig.json file:

1
{
2
"compilerOptions": {
3
"outDir": "dist",
4
"module": "ESNext",
5
"target": "ES6",
6
"declaration": true,
7
"strict": true,
8
"esModuleInterop": true
9
},
10
"include": ["src"]
11
}

Implement the Library Code

Inside packages/my-library, create a src folder and an index.ts file:

Terminal window
mkdir src && touch src/index.ts

Write a simple function inside src/index.ts:

1
export function greet(name: string): string {
2
return `Hello, ${name}!`;
3
}

Build the Library

Add a build script to package.json:

1
{
2
"scripts": {
3
"build": "tsup src/index.ts --format esm,cjs --dts"
4
}
5
}

Run the build command:

Terminal window
pnpm build

If you want to use the library in another package within the monorepo, create another package (e.g., app) and add my-library as a dependency:

Terminal window
pnpm add my-library --filter app

Now, you can import and use the library inside the app package.

1
import { greet } from "my-library";
2
console.log(greet("World"));

✅ Conclusion

Setting up a TypeScript library in a monorepo structure provides a scalable way to manage dependencies, reuse code, and streamline development. By leveraging pnpm, Turborepo, and TypeScript, you can build and maintain a high-performance library efficiently.