Build and publish a TypeScript package to npm
By Flavio
Updated
Tagged: Node.js
Build a TypeScript 7 library for npm with tsdown: ESM and CommonJS outputs, type declarations, exports, tests, semantic versions, and trusted publishing.
Publishing a TypeScript package is easy until the package is imported by another project.
Then details matter:
- does it work with ESM?
- does it work with CommonJS?
- can TypeScript find the types?
- are internal source files accidentally public?
- does the npm tarball contain what we expect?
In this tutorial we’ll build and publish a small package called tiny-duration.
It converts milliseconds into a readable duration:
formatDuration(90500) // "1m 30s"
Create the package
This tutorial assumes you know TypeScript’s type syntax. If you need to start there, take my free TypeScript course, which is also available as a PDF or EPUB.
Start by creating the project folder, initializing the package, and installing the dependencies:
mkdir tiny-duration
cd tiny-duration
npm init -y
npm pkg set type=module
npm install --save-dev typescript@7 tsdown vitest
tsdown builds the package, and it uses TypeScript 7 to generate the type declarations. Older versions of this tutorial used tsup, which isn’t actively maintained anymore. Its README now points to tsdown, and tsdown keeps a very similar config.
tsdown needs a recent Node.js, like a current Node.js 24 release. On an older Node.js 22 release, npm quietly installs an older tsdown that refuses TypeScript 7 with an ERESOLVE error.
We also need the npm pkg set type=module line. A fresh npm init -y writes "type": "commonjs", and with that tsdown fails to load its TypeScript config file.
Create src/index.ts:
export type FormatDurationOptions = {
compact?: boolean
}
export function formatDuration(
milliseconds: number,
options: FormatDurationOptions = {}
): string {
if (!Number.isFinite(milliseconds) || milliseconds < 0) {
throw new TypeError('milliseconds must be a non-negative number')
}
const totalSeconds = Math.floor(milliseconds / 1000)
const minutes = Math.floor(totalSeconds / 60)
const seconds = totalSeconds % 60
if (options.compact) {
return `${minutes}:${String(seconds).padStart(2, '0')}`
}
const parts = []
if (minutes > 0) {
parts.push(`${minutes}m`)
}
if (seconds > 0 || parts.length === 0) {
parts.push(`${seconds}s`)
}
return parts.join(' ')
}
Everything exported from src/index.ts is your public API, so keep that list small.
Configure TypeScript
Create tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"declaration": true,
"skipLibCheck": true
},
"include": ["src"]
}
strict is especially important for a library. A weak type hidden inside the package becomes a weak type in every project that installs it.
Build ESM, CommonJS, and declarations
Create tsdown.config.ts:
import { defineConfig } from 'tsdown'
export default defineConfig({
entry: ['src/index.ts'],
format: ['esm', 'cjs'],
dts: true,
clean: true,
sourcemap: true,
})
Add scripts to package.json:
{
"scripts": {
"build": "tsdown",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"prepack": "npm run typecheck && npm run test && npm run build"
}
}
tsdown doesn’t check your types. It builds the package even if the code has a type error. The typecheck script runs the TypeScript compiler as a checker only (--noEmit means it writes no files), so a type error stops prepack before anything gets packed.
Run:
npm run build
The dist directory contains:
dist/
index.cjs
index.cjs.map
index.d.cts
index.d.mts
index.mjs
index.mjs.map
tsdown uses the .mjs and .cjs extensions for Node.js libraries. Each file says which module system it uses, whatever the type field says. The declarations follow the same rule, with .d.mts for ESM and .d.cts for CommonJS.
You may also see a warning that TypeScript 7 doesn’t have a stable API yet. The build still produces the declarations.
Define package exports
Edit package.json:
{
"name": "tiny-duration",
"version": "1.0.0",
"description": "Format a duration in milliseconds",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.cts",
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
},
"files": [
"dist"
],
"sideEffects": false
}
Choose a real package name that’s available on npm. Scoped packages like @yourname/tiny-duration avoid most naming collisions.
The exports map is the public entry point.
ESM consumers receive index.mjs and index.d.mts. CommonJS consumers receive index.cjs and index.d.cts. The top-level main, module and types fields are fallbacks for older tools that don’t read exports.
The files array is an allowlist for the published tarball. It prevents tests, source configuration, and local notes from being published accidentally.
Only set sideEffects: false when importing the package doesn’t perform global work. Bundlers use this hint for tree shaking.
Add tests
Create src/index.test.ts:
import { describe, expect, test } from 'vitest'
import { formatDuration } from './index'
describe('formatDuration', () => {
test('formats minutes and seconds', () => {
expect(formatDuration(90_500)).toBe('1m 30s')
})
test('supports compact output', () => {
expect(formatDuration(90_500, { compact: true })).toBe('1:30')
})
test('rejects negative values', () => {
expect(() => formatDuration(-1)).toThrow(TypeError)
})
})
Run the tests:
npm test
These tests only run against your source files. You also want to test the exact package people will install.
Inspect the npm tarball
Create README.md and LICENSE before packing (we’ll cover what goes in the README next). Pick a license you understand and put its full text in LICENSE.
Run a dry run first:
npm pack --dry-run
npm prints every file that will end up in the published package.
Check that these are included:
distfilespackage.jsonREADME.mdLICENSE
And make sure none of these snuck in:
.env- test fixtures
- private keys
- editor files
- large source maps you didn’t mean to ship
Next, create the tarball:
npm pack
Install it in a temporary project to test it the way a consumer will:
mkdir /tmp/tiny-duration-consumer
cd /tmp/tiny-duration-consumer
npm init -y
npm install /path/to/tiny-duration/tiny-duration-1.0.0.tgz
Test ESM in a test.mjs file:
import { formatDuration } from 'tiny-duration'
console.log(formatDuration(90500))
Test CommonJS in a test.cjs file:
const { formatDuration } = require('tiny-duration')
console.log(formatDuration(90500))
Testing the tarball catches broken export paths that your source tests can’t see.
Write the README before publishing
A useful package README answers:
- what does this package do?
- how do I install it?
- what’s the smallest working example?
- what inputs and outputs does the API use?
- which runtimes are supported?
Make sure the code examples run as written. The first snippet shouldn’t depend on setup explained three sections later.
Add repository and license metadata to package.json:
{
"repository": {
"type": "git",
"url": "git+https://github.com/yourname/tiny-duration.git"
},
"license": "MIT",
"engines": {
"node": ">=18"
}
}
And don’t list runtime support you haven’t tested.
Choose the next version
npm package versions usually follow semantic versioning:
- patch: bug fix that keeps the public API as it is
- minor: backward-compatible feature
- major: breaking change
You can bump the version and create a Git tag in one step:
npm version patch
Don’t try to reuse a published version. The npm registry won’t let you overwrite a package at the same name and version.
Publish manually once
Create an npm account, enable two-factor authentication, and log in:
npm login
For an unscoped public package:
npm publish
For a new scoped public package:
npm publish --access public
The prepack script runs the typecheck, tests, and build before creating the tarball.
Once it’s published, install the live version from the registry in your temporary project. Don’t stop just because the package page shows up.
Publish from GitHub Actions without a token
npm trusted publishing uses OpenID Connect. GitHub Actions gets short-lived permission to publish a specific package, so you don’t have to store a long-lived npm token.
In your npm package settings, add a trusted publisher for the repository and workflow filename, and enable the npm publish action.
Set its GitHub Actions environment to release. We’ll use that same name in the workflow.
Create .github/workflows/publish.yml:
name: publish
on:
release:
types: [published]
permissions:
contents: read
id-token: write
jobs:
publish:
runs-on: ubuntu-latest
environment: release
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 24
registry-url: https://registry.npmjs.org
package-manager-cache: false
- run: npm install --global npm@^11.5.1
- run: npm ci
- run: npm run typecheck
- run: npm test
- run: npm run build
- run: npm publish
Trusted publishing requires npm 11.5.1 or newer and a supported Node.js version, so the workflow installs a compatible npm release explicitly. Setting package-manager-cache: false turns off setup-node’s automatic dependency cache so a poisoned cache can’t expose the short-lived publish token.
When you publish a public package from a public repository through a trusted publisher, npm can also attach provenance linking the package back to its source and workflow.
A few settings are worth locking down on your release workflow:
- publish only from a protected environment
- require review before a release runs
- keep the workflow filename stable
- make sure
repository.urlmatches the exact source repository - build from the release commit, not an arbitrary branch
Keep the package maintainable
Once you export a function or type, users will start depending on it, so only add new exports when you plan to keep them around.
For each new release, run through the same sequence:
- update and test the public behavior
- bump the semantic version
- inspect the output of
npm pack --dry-run - install and test the packed tarball
- publish through your protected GitHub Actions workflow
- install the published package from the registry to verify it
You can use these same tarball checks when you publish an OpenCode plugin.
Want me to talk about your product? You can sponsor this site.
Related posts about node: