Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 133 ยท Modules and Packages

Creating and Publishing Packages

Build a Node.js package step by step - library layout, the exports map, bin commands, files, versioning and changelogs, npm pack and link, provenance and private registries.

Sooner or later you will write code you want to reuse: a helper shared by three of your projects, a command-line tool, or a library for other developers. The way to share it in the Node.js world is a package: a folder with a package.json that can be installed from the npm registry, from a private registry, from a git URL, or from a local tarball.

This lesson walks through creating a good package: how to lay it out, how to describe its public API with exports, how to ship a command with bin, which files to publish, how to version it, and how to test it locally before anyone else sees it. If you have not read package.json and the npm Registry yet, do that first.

Publishing needs an npm account, the npm command and internet access, none of which exist in our editor. Everything that talks to the registry is shown as read-only commands. Everything else, including building the package folder, loading it through its exports map and running its command, is runnable below.

A small library, from nothing

We will create a package called slugify-lite that turns titles into URL slugs. A good first layout is small:

TEXT
slugify-lite/
  package.json
  README.md
  LICENSE
  CHANGELOG.md
  src/
    index.js
  test/
    index.test.js

Source code goes in src/ (or lib/), tests in test/, and the root holds documentation and metadata. The next example creates exactly this layout in the editor's temporary folder and uses the package the way a consumer would, through node_modules.

Node.js Building and using a package folder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node found slugify-lite because its folder sits in node_modules. That is all npm install does after downloading: it unpacks the files into that folder. Note the import is by package name; the exports field decided which file answers.

The exports map in practice

The exports field is the heart of a modern package. It lists the public entry points, and everything else becomes private. A package with several entry points looks like this:

JSON
{
  "name": "slugify-lite",
  "type": "module",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js",
      "require": "./dist/index.cjs"
    },
    "./transliterate": "./dist/transliterate.js",
    "./package.json": "./package.json"
  }
}

Users then import slugify-lite or slugify-lite/transliterate, and nothing else. Conditions are checked in order, so put types first (TypeScript looks for it) and default last as a fallback. Because "./package.json" is not exported by default, tooling often needs it listed explicitly.

Node.js Private files stay private (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

With an exports map, the maintainer can move or delete internal.js in a later release without it being a breaking change, because no consumer could legally depend on it. This is the biggest reason to always write one.

You can also use a package from inside itself by its own name (self-referencing) once it has an exports field, which keeps tests and examples identical to what users write: import { slugify } from 'slugify-lite'.

Shipping a command with bin

Some packages are tools, not libraries. The bin field maps command names to files. When a user installs your package, npm creates a link (and on Windows a small .cmd wrapper) so the command works in the terminal.

JSON
{
  "name": "slugify-lite",
  "bin": { "slugify": "./bin/slugify.js" }
}

The file must start with a shebang line so Unix systems know which program runs it:

JavaScript
#!/usr/bin/env node
import { slugify } from '../src/index.js';

const input = process.argv.slice(2).join(' ');
console.log(slugify(input));

#!/usr/bin/env node finds node on the user's PATH. npm marks the file executable at install time. We cannot type commands in our editor, but we can run the same file with Node itself. Node accepts a shebang line at the top of any script and ignores it.

Node.js Running a bin script

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Good CLI manners: print results to stdout, errors to stderr, and exit with a non-zero code on failure. Building Command-Line Tools goes much deeper.

Choosing what gets published

By default npm publishes almost everything in the folder, except what is listed in .gitignore or .npmignore, plus a few things always excluded. That tends to leak tests, config files and sometimes secrets. The safer approach is an allow-list: the files field names exactly what to include. package.json, README, LICENSE and the files in main and bin are always added.

JSON
{
  "files": ["src", "bin", "CHANGELOG.md"]
}

On your machine, npm pack --dry-run prints the file list without creating anything, and npm pack creates the real tarball (slugify-lite-1.0.0.tgz). Always check it before the first publish. Node 22 has fs.glob, which lets us build a small stand-in for that check:

Node.js Which files would be published?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The allow-list picks src and bin, adds the always-included files, and leaves the tests, notes and .env out. Treat the real npm pack --dry-run output as the final word, though.

Versioning and changelogs

Follow semantic versioning: bug fixes bump the patch, backwards-compatible features bump the minor, and breaking changes bump the major. What counts as breaking? Anything a user could reasonably depend on: removed or renamed exports, changed return values, dropped Node versions (raising engines), changed default behaviour, and removed files listed in exports.

On your machine:

Terminal
npm version patch   # 1.0.0 -> 1.0.1, updates package.json, commits and tags in git
npm version minor   # 1.0.1 -> 1.1.0
npm version major   # 1.1.0 -> 2.0.0
npm version prerelease --preid=beta   # 2.0.1-beta.0

Keep a CHANGELOG.md so users can see what changed. A simple convention is a section per version with headings such as Added, Changed, Fixed and Removed, newest first. Tools like changesets or release-please can generate versions and changelogs from commit messages or small change files. This stand-in shows what npm version does to the file itself:

Node.js What npm version does

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Resetting the lower numbers matters: a minor bump zeroes the patch, a major bump zeroes both.

Testing a package before publishing

A package can pass its own unit tests and still be broken for users, for example because files forgot a directory or exports points at a missing file. Test the package as installed:

Terminal
npm pack                              # create slugify-lite-1.0.0.tgz
cd ../some-test-project
npm install ../slugify-lite/slugify-lite-1.0.0.tgz   # install exactly what would be published

or link it during development:

Terminal
cd slugify-lite && npm link           # register a global symlink to this folder
cd ../some-test-project && npm link slugify-lite   # use the symlink in a project

npm link makes a symbolic link in node_modules, so edits in the package folder show up immediately. Because our editor lets us create symlinks, we can imitate the idea:

Node.js What npm link does

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Editing my-lib/index.js changes what the app sees, since there is only one copy of the file. The link also explains a classic bug: a linked package resolves its own dependencies from its real location, so it can end up with a second copy of a shared library such as React.

Publishing

When the tarball looks right, publishing is a few commands (read-only, what you would type):

Terminal
npm login                    # once per machine
npm publish --dry-run        # rehearse without uploading
npm publish                  # publish an unscoped public package
npm publish --access public  # first publish of a scoped package such as @acme/tools

A few rules and habits worth knowing:

  • Names are first-come, first-served. Check npm view slugify-lite first; scoped names (@yourname/pkg) avoid collisions.
  • Published versions are immutable. You cannot overwrite 1.0.0. You can npm deprecate a bad version or, within a short window, unpublish it, but the right fix is a new patch release.
  • Turn on two-factor authentication for your npm account and use granular access tokens or trusted publishing for automation instead of a personal password.
  • Provenance. When you publish from a supported CI system (such as GitHub Actions) with npm publish --provenance, npm records a signed statement of which repository and commit built the tarball. Users can see a "built and signed on" badge, which makes tampering much harder.
  • Private packages. Scoped packages can be private (paid), or you can run a private registry such as Verdaccio, GitHub Packages or a cloud provider's registry. Point npm at it with a line in .npmrc: @acme:registry=https://registry.example.com/.
  • Keep it small. Fewer dependencies mean fewer breakages and a smaller attack surface for your users. If you can write ten lines yourself, do.

A pre-publish checklist

  1. name, version, description, license, repository and engines are filled in.
  2. type is set, and exports lists every public entry point (and ./package.json if tools need it).
  3. files is an allow-list and npm pack --dry-run shows no secrets, no tests, no junk.
  4. A README shows installation, a minimal example and the API; a LICENSE file is present.
  5. Tests pass, including a smoke test that imports the packed tarball in a clean project (both import and, if you ship CommonJS, require).
  6. The changelog and version bump match the size of the change.
  7. For libraries, TypeScript types are included (see TypeScript in Node.js).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when a consumer imports a file that is not listed in the package's exports map?

    Once exports exists, only the listed paths can be imported. Everything else is private, so maintainers can change internals without breaking users.
  2. 2. Why does a bin script start with #!/usr/bin/env node?

    The shebang line selects the interpreter when the file is executed directly. Node itself ignores that first line when it loads the script.
  3. 3. You fix a bug without changing the API. Which command and version change fits semver?

    Bug fixes are patch releases. Published versions cannot be overwritten, so every fix is a new version.
  4. 4. Why is the files field in package.json considered safer than .npmignore?

    An ignore list publishes everything you forgot to exclude, including secrets and tests. An allow-list publishes only what you name, plus package.json, README, LICENSE and the main and bin files.
  5. 5. What is the main benefit of npm pack followed by installing the tarball in a test project?

    Packing exercises the files list and the exports map, so mistakes like a missing folder show up before users hit them.

Summary

  • A package is a folder with a package.json; installing it just unpacks that folder into node_modules.
  • exports defines the public entry points and hides everything else; use conditions (types, import, require, default) when you ship several formats.
  • bin maps command names to scripts that start with #!/usr/bin/env node; write results to stdout, errors to stderr and exit non-zero on failure.
  • Use the files allow-list and check npm pack --dry-run before every first publish.
  • Follow semver: patch for fixes, minor for compatible features, major for breaking changes, and keep a changelog.
  • Test the packed tarball (or npm link) in a separate project before publishing.
  • Published versions are immutable; secure your account with 2FA and prefer provenance and trusted publishing from CI.
  • Private code can live in scoped packages or a private registry configured in .npmrc.

Next: TypeScript in Node.js shows how to run .ts files directly and how to type your packages.