Skip to main content

Programming languages · Advanced · 22 min

Publish a TypeScript library to npm with type declarations

By Padding · Updated 18 Nov 2026
node:26 image · Node.js 26 LTS · npm 11.20 · TypeScript 7.0.2

You will package a small TypeScript slugify library with declaration files, an exports map and a files list, prove what ships with npm pack, test the tarball in a separate project, lint it with publint and attw, and know how to publish it with provenance.

On this page

A TypeScript library on npm ships JavaScript, not TypeScript. What makes it pleasant to use is everything around that JavaScript: declaration files (.d.ts) so editors and tsc know the types, an exports map that says which files other people may import, and a files list that keeps your tests, configs and secrets out of the tarball. Most broken packages are broken in one of those three places, not in their code.

In this tutorial you build @example/slugify, a function that turns titles into URL slugs, and package it properly. You compile it with TypeScript 7, look inside the exact tarball npm would upload, install that tarball into a second project to prove the imports and types work, and run two packaging linters. Publishing itself comes last, as a step you run when you have an npm account. Everything before it runs on your machine with no account.

The library treats text from many languages fairly. It removes accents from Latin letters, so a Yoruba name such as Àdùnní becomes adunni, and it leaves other scripts, such as Devanagari or Ge'ez, as they are, because stripping their marks changes the words.

Step 1 · Create the library and install the tools

Make a demo folder with the library inside it. Write package.json by hand, because every field in it decides something about what you publish:

Bash
mkdir -p ~/slugify-demo/slugify
cd ~/slugify-demo/slugify
cat > package.json <<'JSON'
{
  "name": "@example/slugify",
  "version": "0.1.0",
  "description": "Turn any text into a URL-friendly slug",
  "license": "MIT",
  "type": "module",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "default": "./dist/index.js"
    },
    "./package.json": "./package.json"
  },
  "files": ["dist", "src"],
  "sideEffects": false,
  "engines": { "node": ">=22" },
  "publishConfig": { "access": "public" },
  "scripts": {
    "clean": "node -e \"fs.rmSync('dist', { recursive: true, force: true })\"",
    "build": "npm run clean && tsc",
    "check": "publint --strict && attw --pack . --profile esm-only",
    "prepublishOnly": "npm run build"
  }
}
JSON

@example is a placeholder scope. Keep it while you follow along, and change it to your own npm username before you publish, in the last steps.

What the fields do:

  • type: module makes every .js file in the package an ES module.
  • exports is the public surface. "." is what import ... from "@example/slugify" loads. Inside it, types must come first: TypeScript picks the first condition that matches, and default matches everything. Listing ./package.json lets tools read your metadata. Any other path inside the package is now off limits to users, which you will see fail on purpose later.
  • files is an allow-list. Only dist and src ship, plus the files npm always includes: package.json, README and LICENSE.
  • sideEffects: false tells bundlers they may drop the module when nothing from it is used.
  • publishConfig.access is needed because scoped packages are private by default on npm.
  • prepublishOnly runs before npm publish and never before npm install or npm pack. That makes a clean build the last thing that happens before an upload.

Now install the compiler and the two linters as development dependencies, pinned to exact versions:

Bash
npm install --save-dev --save-exact typescript@7.0.2 publint@0.3.25 @arethetypeswrong/cli@0.18.5
npx tsc --version

Development dependencies are not installed for people who install your library, so tools you build with never reach their node_modules.

Check it worked

npx tsc --version prints Version 7.0.2. package.json now ends with a devDependencies block that lists the three packages with no ^ in front of the versions.

Step 2 · Write the library and its tsconfig.json

The whole library is one file. The @example line in the comment shows up in editors when someone hovers over the function:

Bash
mkdir -p src
cat > src/index.ts <<'TS'
export interface SlugifyOptions {
  /** Text placed between words. Defaults to "-". */
  separator?: string;
  /** Longest slug to return. Cuts at the last whole word that fits. */
  maxLength?: number;
}

const LATIN_ACCENTS = /(\p{Script=Latin})\p{M}+/gu;
const NOT_LETTER_OR_DIGIT = /[^\p{L}\p{M}\p{N}]+/gu;

/**
 * Turn any text into a lowercase, URL-friendly slug.
 *
 * @example slugify("Àdùnní & Ọ̀ṣun") // "adunni-osun"
 */
export function slugify(text: string, options: SlugifyOptions = {}): string {
  const separator = options.separator ?? "-";
  const words = text
    .normalize("NFKD")
    .replace(LATIN_ACCENTS, "$1")
    .normalize("NFC")
    .toLowerCase()
    .split(NOT_LETTER_OR_DIGIT)
    .filter((word) => word.length > 0);

  let slug = words.join(separator);
  const max = options.maxLength;
  if (max !== undefined && slug.length > max) {
    const cut = slug.slice(0, max);
    const endsOnWord = slug.startsWith(separator, max);
    const lastBreak = cut.lastIndexOf(separator);
    slug = endsOnWord || lastBreak <= 0 ? cut : cut.slice(0, lastBreak);
  }
  return slug;
}
TS

normalize("NFKD") splits a letter such as ọ̀ into a base letter and its combining marks. The first regular expression removes marks only when they follow a Latin letter. \p{M} stays in the word pattern, so the vowel signs in Hindi or Bengali text stay attached to their letters.

The compiler settings are where a library differs from an app:

Bash
cat > tsconfig.json <<'JSON'
{
  "compilerOptions": {
    "target": "es2022",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "rootDir": "src",
    "outDir": "dist",
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,
    "isolatedDeclarations": true,
    "strict": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "types": []
  },
  "include": ["src"]
}
JSON
  • declaration writes a .d.ts file next to each .js file. Without it, users of your package get no types.
  • declarationMap writes a .d.ts.map that points from each declaration back to the line in src/index.ts. Editors use it for Go to Definition, which is why src is in the files list.
  • isolatedDeclarations makes the compiler insist on explicit types for everything you export, such as the : string return type. The public API is then written down in the source, not inferred, and a refactor cannot change it by accident.
  • types: [] loads no global type packages. The library uses no Node.js APIs, so it should not depend on @types/node.

Check it worked

Bash
npx tsc --noEmit

The command prints nothing and exits successfully. If you delete : string after the parameter list in src/index.ts, it reports an error asking for an explicit return type annotation, which is isolatedDeclarations at work. Put it back before you go on.

Step 3 · Build and read the declarations

Build with the script, not with tsc directly, so that the old dist is removed first. Without the clean step, a file you renamed or deleted in src would still sit in dist and still ship:

Bash
npm run build
ls dist
cat dist/index.d.ts

Check it worked

ls dist shows four files: index.d.ts, index.d.ts.map, index.js and index.js.map. index.d.ts holds the SlugifyOptions interface with its comments and the line export declare function slugify(text: string, options?: SlugifyOptions): string;. The default value of options has become a ?, because declarations describe types, not behaviour.

Step 4 · See exactly what would ship

npm pack --dry-run builds the file list npm would upload and prints it, without writing anything:

Bash
npm pack --dry-run

Look at the Tarball Contents section. It lists LICENSE and README.md only if you have them, then the four files in dist, package.json and src/index.ts. It does not list tsconfig.json, package-lock.json or node_modules. Add a README.md and a LICENSE file before you publish for real: the README becomes the package page on npmjs.com.

For a list you can search, ask for JSON. This prints one line per shipped file under dist or src, and fails if there are none:

Bash
npm pack --dry-run --json | grep -E '"path": "(dist|src)/'

Check it worked

The second command prints five lines, from "path": "dist/index.d.ts" to "path": "src/index.ts". The first reports a package size of about 2 kB. Small packages matter to the people installing them, many of whom pay for data by the megabyte on prepaid mobile plans, so check this list each time you add a folder to the project.

Step 5 · Lint the package with publint and attw

Two tools check the packaging rather than the code. publint reads package.json and the packed file list, and finds problems such as an exports entry that points at a missing file or a types condition in the wrong place. With --strict, warnings fail the run as well as errors:

Bash
npx publint --strict

attw, from the Are the Types Wrong project, packs the library and resolves every entry point the way TypeScript would under each module setting, then reports where the types and the JavaScript disagree. Run it with its default settings first. This run is meant to fail, so the command reports an error if attw finds nothing:

Bash
if npx attw --pack .; then echo "expected attw to report problems"; false; else echo "attw exited with status $?"; fi

The table has a row per module resolution mode. node16 (from ESM) and bundler are green. node10 shows Resolution failed, because that old mode ignores exports, and node16 (from CJS) warns that the package can only be loaded with a dynamic import (attw labels it along the lines of ESM (dynamic import only)), because the package has no CommonJS build. Both are true, and both are a choice, not a bug: this library is ESM only, and recent Node.js releases can also require() an ES module in most cases. Tell attw about that choice with a profile:

Bash
npx attw --pack . --profile esm-only

The check script in package.json runs both linters this way, so run npm run check before each release and in CI.

Check it worked

publint reports no errors or warnings and exits successfully (it prints a short all-clear line such as All good!). The first attw run ends with attw exited with status 1. The second marks the CommonJS rows as ignored and exits successfully. If you swap the order of types and default in exports, publint reports that types must come first. Swap them back.

Step 6 · Install the tarball in a separate project

Linters reason about the package. A real install proves it. Write the tarball to disk, then create a second project next to the library and install the file:

Bash
npm pack
cd ~/slugify-demo
mkdir -p app
cd app
cat > package.json <<'JSON'
{
  "name": "slugify-app",
  "private": true,
  "type": "module"
}
JSON
npm install ../slugify/example-slugify-0.1.0.tgz
npm install --save-dev --save-exact typescript@7.0.2 @types/node@26.6.11

npm pack names the file after the package, with the scope folded in: example-slugify-0.1.0.tgz. Installing from the tarball, not from the folder, gives the app exactly what npm would upload and nothing more. A folder install creates a link to your source tree and hides mistakes in files and exports.

The app gets its own strict tsconfig.json, so the compiler checks the package from outside, the way your users' compilers will:

Bash
cat > tsconfig.json <<'JSON'
{
  "compilerOptions": {
    "target": "es2022",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "strict": true,
    "noEmit": true,
    "verbatimModuleSyntax": true,
    "erasableSyntaxOnly": true,
    "types": ["node"]
  },
  "include": ["*.ts"]
}
JSON

erasableSyntaxOnly allows only TypeScript that Node.js can run by removing the types, so the app's files can run with node directly. types: ["node"] loads @types/node, because the app's test imports node:test and node:assert/strict. The library keeps types: []: it uses no Node.js APIs, and its users should not inherit a Node.js types dependency from it.

Check it worked

Bash
ls node_modules/@example/slugify node_modules/@example/slugify/dist

The package folder holds dist, package.json and src, and dist holds the same four files you built. There is no tsconfig.json and no node_modules inside it.

Step 7 · Check imports and types from the consumer

Write a test that imports the library by its package name, the way any user would, and runs it with the Node.js test runner:

Bash
cat > slugify.test.ts <<'TS'
import { test } from "node:test";
import assert from "node:assert/strict";
import { slugify, type SlugifyOptions } from "@example/slugify";

test("removes Latin accents", () => {
  assert.equal(slugify("Àdùnní & Ọ̀ṣun: a Lagos love story"), "adunni-osun-a-lagos-love-story");
});

test("keeps other scripts whole", () => {
  assert.equal(slugify("हिन्दी में समाचार"), "हिन्दी-में-समाचार");
});

test("respects the options", () => {
  const options: SlugifyOptions = { separator: "_", maxLength: 12 };
  assert.equal(slugify("Prepaid data tips for 2027", options), "prepaid_data");
});
TS
npx tsc
node --test slugify.test.ts

npx tsc type-checks the test against the installed .d.ts, so the import of the SlugifyOptions type proves the declarations ship and resolve. Then make sure the types reject bad input. Add a file with a mistake in it:

Bash
cat > wrong.ts <<'TS'
import { slugify } from "@example/slugify";

slugify("Hello", { maxLength: "20" });
TS
if npx tsc > tsc.log; then echo "expected a type error"; false; else echo "tsc exited with status $?"; fi
cat tsc.log
grep -q "wrong.ts(3,20): error TS2322" tsc.log
rm wrong.ts tsc.log

Last, try to reach past the exports map into a file you did not make public:

Bash
node --input-type=module -e '
try {
  await import("@example/slugify/dist/index.js");
  console.log("deep import allowed");
  process.exitCode = 1;
} catch (error) {
  console.log(error.code);
  if (error.code !== "ERR_PACKAGE_PATH_NOT_EXPORTED") process.exitCode = 1;
}'

Check it worked

The test run reports pass 3 and fail 0. The mistake produces wrong.ts(3,20): error TS2322: Type 'string' is not assignable to type 'number'. and a tsc exited with status line with a non-zero number; the fence fails if tsc accepts the bad call. The deep import prints ERR_PACKAGE_PATH_NOT_EXPORTED: only the paths in exports are public, so you can reorganise dist later without breaking anyone.

Open slugify.test.ts in VS Code or another editor with TypeScript support and use Go to Definition on slugify. The editor opens node_modules/@example/slugify/src/index.ts, not the .d.ts file, because of the declaration map. You can check the map's target exists from the terminal:

Bash
node -e '
const map = JSON.parse(fs.readFileSync("node_modules/@example/slugify/dist/index.d.ts.map", "utf8"));
const source = path.join("node_modules/@example/slugify/dist", map.sources[0]);
console.log(source, fs.existsSync(source) ? "exists" : "missing");'

It prints node_modules/@example/slugify/src/index.ts exists.

Step 8 · Publish to npm, by hand and from CI

First rehearse the publish. --dry-run runs prepublishOnly, so it rebuilds dist from clean, packs, and stops before the upload. It works without logging in:

Bash
cd ~/slugify-demo/slugify
npm publish --dry-run

The output shows the build scripts running, the tarball contents again, possibly a warning about not being logged in, and a final line + @example/slugify@0.1.0.

To publish for real, rename the package to your own scope. Replace your-npm-username with your npm username. Check the name is free with npm view, which should answer with a 404 error. Then log in and publish:

Bash
npm pkg set name=@your-npm-username/slugify
npm view @your-npm-username/slugify
npm login
npm publish

npm login opens a browser to sign in, so no password goes into your shell history. With two-factor authentication on, npm asks for a one-time code before the upload. A published version can never be replaced: to fix a mistake, publish a new version. npm's unpublish policy limits removing packages, so read it before you publish a test package you mean to delete.

Check it worked

npm view @your-npm-username/slugify now shows version 0.1.0, the description and the dist-tags line latest: 0.1.0. In a fresh folder, npm install @your-npm-username/slugify gives the same result as the tarball did.

Publish from CI with provenance

For later releases, let CI publish. npm's trusted publishing connects a package to one workflow file in one repository through OpenID Connect, so there is no long-lived npm token to store or leak. It needs npm 11.5.1 or later, which Node.js 26 has, and a GitHub-hosted runner (GitLab.com and CircleCI cloud are supported too). Trusted publishers are set in the package's settings on npmjs.com, so publish the first version by hand as above. Then add a trusted publisher there with your GitHub user or organisation, repository and the workflow file name, release.yml.

Before the first CI release, add a repository field to package.json. npm checks the provenance it generates against repository.url, and if the field is missing or names a different repository, the publish fails with an error that repository.url does not match. Replace the placeholders <your-user> and <your-repo> with your GitHub user or organisation and repository:

JSON
"repository": {
  "type": "git",
  "url": "git+https://github.com/<your-user>/<your-repo>.git"
}

The workflow runs when you push a version tag. Add it as .github/workflows/release.yml:

YAML
name: Release
on:
  push:
    tags: ["v*"]

permissions:
  contents: read
  id-token: write

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - uses: actions/setup-node@v6
        with:
          node-version: "26"
          registry-url: "https://registry.npmjs.org"
      - run: npm ci
      - run: npm run build
      - run: npm run check
      - run: npm publish

id-token: write lets the job ask GitHub for a short-lived identity token, which npm exchanges for permission to publish this one package. When a public package is published this way from a public repository, npm also adds a provenance attestation without the --provenance flag. Provenance is a signed, publicly logged record of which repository, commit and workflow built the tarball. The npm page then shows where the package came from, and anyone can check that it was built from your source. It does not prove the code is safe, only where it came from.

Step 9 · Clean up

Remove both demo projects. Node.js and npm stay installed. If you published a package, it stays on npm:

Bash
cd ~
rm -rf ~/slugify-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.