Skip to content

Premium sponsors

Prisma

Compilation

Compiling your TypeScript files to JavaScript is not handled by tsx, but it's a necessary step in most setups.

Should I publish TypeScript files?

No. While tsx is capable of running TypeScript files in dependencies if need be (e.g. monorepos), it's highly discouraged to publish uncompiled TypeScript. Source files require a specific compilation configuration in tsconfig.json which may not be read, and TypeScript performance will degrade.

Compiling an npm package

npm packages are distinguished from applications by defining package entry-points in package.json.

pkgroll is the recommended bundler for projects using tsx. It's developed by the same author and used to compile tsx.

Given your source files are in the src directory, it automatically infers how to build your package based on the entry points defined in package.json by outputting them to the dist directory.

Setup

Basic setup

Set your entry-point in exports:

json5
// package.json
{
    "exports": "./dist/index.mjs"
}
Dual package (CJS & ESM)

Set your CommonJS & Module entry-points in exports:

json5
// package.json
{
    "main": "./dist/index.cjs",
    "module": "./dist/index.mjs",
    "types": "./dist/index.d.cts",

    "exports": {
        "require": {
            "types": "./dist/index.d.cts",
            "default": "./dist/index.cjs"
        },
        "import": {
            "types": "./dist/index.d.mts",
            "default": "./dist/index.mjs"
        }
    }
}
Command-line package

Set your CLI entry-point in bin:

json5
// package.json
{
    "bin": "./dist/cli.mjs"
}

Build

In your directory, simply run pkgroll:

sh
$ npx pkgroll
sh
$ pnpm pkgroll
sh
$ yarn pkgroll

Optionally, add a build script for convenience:

json
// package.json
{
    // Optional: build script
    "scripts": {
        "build": "pkgroll"
    }
}