typescriptnrwl-nxpnpmesbuildpnpm-workspace

Building private Typescript packages in a monorepo


How should private (not published) Typescript libraries in a monorepo be built so they can be shared amongst other libraries and apps (both Node and browser) in the repo? I'm using nx and pnpm to manage the monorepo.

  1. Should they each be transpiled to Javascript, or can the consuming package import the Typescript directly?
  2. How should their pnpm dependancies be configured (dependancies, peerDependancies) such that consuming package doesn't need to list these dependancies, but also prevents multiple copies?
  3. What module format should be used for private packages used in both Node and browser builds?
  4. Do the libraries need to be bundled with esbuild/webpack/etc?

I realize there are multiple questions, but they all come down to what the build step for the libraries should look like. I am currently trying just tsc and es2020 modules, but am having issues, such as Jest failing to import these libraries in a dependent library.


Solution

  • You build all the packages together in one step. They can have different tsconfig build configurations though, if you prefer different code styles.

    You reference the typescript files although depending on your tsconfig you can probably omit the file extension. Your imports can use the package name as reference import {Foo} from '@CompanyName/fooLib' and pnpm workspaces will link them to the right package.

    Dependencies should be referenced in package.json without version: "@CompanyName/fooLib": "*"as you will only use the most current version of shared libs, unless you do publishing.

    The bundling depends on your framework, project size etc. There is also Turbopack, Vite (with and without SWC), so this can't be answered without knowing how much speed or LTS is important for you.