← Back to articles

What Do You Need to Know Before Publishing an npm Package?

· npm / Node.js / TypeScript / Frontend Engineering

If you are a frontend developer, you have almost certainly used npm.

Whether we install React and Zod with npm install or create a project with npx create-vite, we use code published to npm by other developers every day.

But what if we want to publish a tool of our own so other developers can use it? What do we need to understand?

The most direct approach is to create a package.json and run npm publish. That alone, however, does not explain how an npm package actually works.

For example:

To answer these questions, we need to start with the two main ways npm packages are used.


1. Are You Publishing a Library or a CLI?

Before discussing publication, we need to establish one idea:

An npm package is a unit of code distribution, rather than a particular way of running a program.

The npm Registry stores and distributes software packages. Developers upload packaged code, and others download and install it using package managers such as npm, pnpm, or Yarn.

How that code is used after installation depends on the interfaces the package provides.

For the most common use cases, we can group packages into libraries and command-line tools (CLIs).

This is a useful distinction, rather than two mutually exclusive package types defined by npm. A single package can provide both a library API and a CLI.

1.1 What Is a Library?

A library is typically installed first and then imported through JavaScript’s module system.

For example, to validate data with Zod:

npm install zod

Then use it in our code:

import { z } from 'zod'

const UserSchema = z.object({
  name: z.string(),
  age: z.number()
})

const user = UserSchema.parse({
  name: 'Tom',
  age: 18
})

Here, Zod is not running as a standalone program. It exposes JavaScript APIs that our application calls.

Other examples include:

For this kind of package, the central question is:

When a user writes import { xxx } from 'package-name', which file should the runtime load?

That brings us to fields such as exports and main in package.json, and to Node.js module resolution.

1.2 What Is a CLI Package?

CLI stands for Command Line Interface.

A CLI package primarily exposes functionality through terminal commands. For example:

npx create-vite my-app

This runs Vite’s project scaffolding tool and creates a project named my-app in the current directory.

There is nothing particularly mysterious about a scaffolding tool.

It is a program launched from the command line that uses Node.js filesystem APIs to create directories, copy templates, and modify configuration files.

We can implement a very basic scaffolding tool in a few dozen lines of JavaScript:

#!/usr/bin/env node

import fs from 'node:fs'
import path from 'node:path'

const projectName = process.argv[2] || 'my-app'
const projectPath = path.resolve(process.cwd(), projectName)

fs.mkdirSync(projectPath, { recursive: true })

fs.writeFileSync(
  path.join(projectPath, 'package.json'),
  JSON.stringify({
    name: projectName,
    version: '1.0.0'
  }, null, 2)
)

console.log(`Created ${projectName}`)

Here:

A real scaffolding tool might offer interactive prompts, template selection, and dependency installation, but the underlying idea is the same.

ESLint, Prettier, and the TypeScript compiler also provide CLIs:

npx eslint .
npx prettier --write .
npx tsc --noEmit

Their functions differ, but each starts a program from the command line.

1.3 What Is the Difference?

For a package author, the main difference is the public entry point.

LibraryCLI
Usageimport / requireTerminal commands
Key configurationexports, mainbin
Main callerOther JavaScript programsUsers, shells, automation scripts
ExamplesZod, Lodashcreate-vite, Prettier

A package can be configured like this:

{
  "name": "my-tool",
  "version": "1.0.0",
  "type": "module",
  "exports": {
    ".": "./dist/index.js"
  },
  "bin": {
    "my-tool": "./dist/cli.js"
  }
}

It can then be imported as a dependency:

import { hello } from 'my-tool'

Or executed from the command line:

npx my-tool

Of course, both entry files must exist and implement the corresponding functionality.

With these two interfaces in mind, we can examine how each works.


2. How Do CLI Packages Work?

Suppose we publish an npm package called my-tool. Users can run our JavaScript with:

npx my-tool

This raises at least three questions:

  1. How does npm know which JavaScript file corresponds to my-tool?
  2. How does the terminal find and execute that file?
  3. If the user has not installed the package, how does npx download and run it?

Let’s look at them in order.

2.1 The bin Field: Declaring Executable Commands

Start with a simple project:

my-tool/
├── package.json
└── bin/
    └── cli.js

Its package.json:

{
  "name": "my-tool",
  "version": "1.0.0",
  "bin": {
    "my-tool": "./bin/cli.js"
  }
}

And bin/cli.js:

#!/usr/bin/env node

console.log('Hello from my-tool!')

The important part is the bin field:

{
  "bin": {
    "my-tool": "./bin/cli.js"
  }
}

It means:

This npm package provides an executable command named my-tool, whose entry file is ./bin/cli.js.

The bin field only declares a mapping between a command and a file. It does not execute any code itself.

What makes the command discoverable is the executable entry the package manager creates during installation.

2.2 How Does npm Turn a JavaScript File into a Command?

Suppose we install the tool in a project:

npm install -D my-tool

npm installs it into the project’s node_modules and creates a command entry based on bin.

On Unix-like systems such as macOS and Linux, the structure typically looks like this:

node_modules/
├── my-tool/
│   ├── package.json
│   └── bin/
│       └── cli.js
└── .bin/
    └── my-tool -> ../my-tool/bin/cli.js

Here, my-tool is a symbolic link pointing to the actual CLI file.

When we run:

./node_modules/.bin/my-tool

The system follows the link to bin/cli.js.

But how does the operating system know it should execute this file with Node.js?

The answer is the shebang at the beginning of the file:

#!/usr/bin/env node

On Unix-like systems, a shebang specifies the interpreter used to run a script.

Here, /usr/bin/env node finds Node.js through the environment, and Node.js executes the JavaScript that follows.

The script also needs the appropriate executable permissions. On Windows, package managers usually generate command wrappers to achieve similar behavior.

The execution flow can be summarized as:

my-tool
   │
   ▼
Shell looks up the command in PATH
   │
   ▼
Finds node_modules/.bin/my-tool
   │
   ▼
Locates the actual bin/cli.js
   │
   ▼
Runs the script with Node.js

2.3 Local Installation vs. Global Installation

The same CLI package can be installed in different places.

Local installation:

npm install -D my-tool

The package is typically located at:

my-project/node_modules/my-tool/

Its command entry is located at:

my-project/node_modules/.bin/my-tool

We can call it from scripts in package.json:

{
  "scripts": {
    "hello": "my-tool"
  }
}

Then run:

npm run hello

npm adds the relevant node_modules/.bin directories to the script environment’s PATH, allowing the script to invoke my-tool directly.

Global installation:

npm install -g my-tool

The installation location depends on npm’s prefix configuration. We can inspect it with:

npm prefix -g
npm root -g

On Unix-like systems, the package is typically located at:

{prefix}/lib/node_modules/my-tool

The executable command is usually linked into:

{prefix}/bin/my-tool

Windows uses a different directory layout.

As long as the global command directory is on the system’s PATH, we can run this directly in a terminal:

my-tool

The essential difference is where the package is installed and how its command becomes available in the execution environment. The package’s code can remain the same.

2.4 How Can npx Run a Package Without Installing It First?

Now consider this invocation:

npx my-tool

The user does not have to run npm install beforehand. That does not mean no installation is needed at all.

In modern npm, npx is an entry point to npm exec. It first tries to reuse available executables or suitable local dependencies.

If the current environment does not have a suitable package, npm may install the required dependencies in its cache environment and then run the command.

On Unix-like systems, the default npm cache directory is typically:

~/.npm

Temporary installation environments used by npx may be located under:

~/.npm/_npx/

With a structure like this:

~/.npm/
└── _npx/
    └── 9c3a5aa8f97744c1/
        ├── package.json
        ├── package-lock.json
        └── node_modules/

Before discussing where that hexadecimal directory name comes from, there is another question: once npx finds a package, how does it choose which command to run?

2.5 How Does npx Decide Which bin to Execute?

As we have seen, the bin field in package.json maps CLI commands to executable files.

For example:

{
  "name": "my-tool",
  "bin": {
    "my-tool": "./bin/cli.js"
  }
}

When a user runs:

npx my-tool

npm finds the my-tool package and executes ./bin/cli.js.

But this raises an interesting question:

Is my-tool in npx my-tool a package name or a command name defined in bin?

When npm needs to infer an executable from a package request, it interprets this as a package request and uses the package’s bin configuration to determine the command. The local command reuse path discussed earlier may instead execute an available command directly.

The package name and command name therefore do not have to be identical.

Case 1: Only One bin Entry

Consider this configuration:

{
  "name": "my-tool",
  "bin": {
    "hello": "./bin/cli.js"
  }
}

The package is named my-tool, while its command is named hello. Even so, this works:

npx my-tool

Because the package declares only one executable, npm can infer which command to run.

Case 2: Multiple bin Entries, One Matching the Package Name

{
  "name": "my-tool",
  "bin": {
    "my-tool": "./bin/main.js",
    "hello": "./bin/hello.js"
  }
}

When we run:

npx my-tool

npm selects my-tool, the command that matches the package name, and executes ./bin/main.js.

For a scoped package such as @example/my-tool, npm matches the unscoped name, my-tool.

Case 3: Multiple Distinct bin Entries, None Matching the Package Name

{
  "name": "my-tool",
  "bin": {
    "hello": "./bin/hello.js",
    "world": "./bin/world.js"
  }
}

Running:

npx my-tool

npm cannot determine which command to execute and reports an error:

npm error could not determine executable to run

There is one special case: if multiple bin names point to the same file, npm can still infer a single executable entry.

How Can We Select a Command Explicitly?

To run the hello command from the my-tool package:

npm exec --package=my-tool -- hello

To specify a version:

npm exec [email protected] -- hello

This separates two concepts:

The executable inference rules can be summarized as follows:

bin configurationResult of npx my-tool
No bin entriesCannot infer an executable; error
Only helloRuns hello
hello and my-tool, pointing to different filesRuns my-tool
hello and world, pointing to different filesCannot infer an executable; error
hello and world, pointing to the same fileCan execute the shared entry

These rules are also described in the official npm exec documentation.

A package name and a binary name are two different concepts.

The former identifies and locates a package; the latter declares the executable commands the package provides.

Through a set of conventions, npx combines package lookup and command selection into a single invocation.

With this distinction in mind, versions, hashes, and cache directories become easier to understand.

2.6 What Is the npx Hash Used For?

Returning to the earlier question: where does the hexadecimal directory name under ~/.npm/_npx/ come from? This is part of how npx locates its cache environments.

In the libnpmexec implementation shipped with npm 10.9.8, when execution requires an npx cache environment, npm computes a hash from the package request specification, or package spec.

The core idea can be simplified to:

const hash = crypto
  .createHash('sha512')
  .update(packageSpec)
  .digest('hex')
  .slice(0, 16)

For example:

my-tool
my-tool@latest
[email protected]
my-tool@^1.0.0

These request strings differ, so they generally produce different hash directories.

For requests involving multiple packages, the implementation also sorts and joins the specs, with special handling for local directory specs.

The key design point is:

The hash determines where a cache environment is stored. It does not determine which version is ultimately used.

In other words:

Package Spec
     │
     ├── Hash computation ──> Cache directory
     │
     └── Version resolution ──> Version to install

These are separate operations.

For example, my-tool and [email protected] may be installed in different npx cache directories even if they resolve to the same version.

2.7 How Does npx Handle Different Versions?

Suppose we run these commands:

npx my-tool
npx my-tool@latest
npx [email protected]
npx my-tool@^1.0.0

Their version semantics differ. Using npm 10.9.8’s npx cache handling as an example:

CommandCached version handling
npx my-toolChecks the registry resolution using the bare-name cache rules
npx my-tool@latestResolves the target version through the latest tag
npx [email protected]Reuses an existing exact version match
npx my-tool@^1.0.0Reuses an existing version satisfying the SemVer range

One point is easy to misunderstand:

A version range is not an automatic update policy.

For example:

npx my-tool@^1.0.0

Suppose the newest matching version at the first installation is 1.2.0. Later, the package publishes 1.5.0 to npm.

Although 1.5.0 also satisfies ^1.0.0, the cached 1.2.0 still meets the requirement, so npm may not update it automatically.

Bare package names are handled differently in the npx cache: npm 10.9.8 specifically checks the registry resolution to determine whether the cached version needs to be replaced.

This discussion concerns the npx cache path. If the current project already contains a suitable dependency, execution may prefer that local version.

We can now outline the full CLI execution flow:

User enters npx my-tool
        │
        ▼
npm parses command and package request
        │
        ▼
Checks existing commands and local dependencies
        │
        ├── Reusable
        │      │
        │      ▼
        │    Execute
        │
        └── Cache environment needed
               │
               ▼
           Computes hash
               │
               ▼
           Checks dependency versions
               │
               ▼
           Installs if needed
               │
               ▼
           Finds bin entry
               │
               ▼
           Sets PATH and executes

The CLI package declares its executable entry. npm, Node.js, and the operating system work together to locate, install, cache, and launch it.


3. How Do Library Packages Work?

With CLIs covered, let’s return to a more familiar usage:

import { z } from 'zod'

This simple statement relies on a complete module resolution mechanism.

First, we need to be clear about responsibilities:

npm installs dependencies into a project. The JavaScript runtime and its module system primarily handle import resolution and module loading.

In Node.js, this is implemented by Node.js itself. In frontend projects, tools such as Vite and Webpack also participate in module resolution and bundling.

3.1 What Does import Actually Do?

Suppose we create this npm package:

my-library/
├── package.json
└── dist/
    └── index.js

Its dist/index.js:

export function hello(name) {
  return `Hello, ${name}!`
}

And package.json:

{
  "name": "my-library",
  "version": "1.0.0",
  "type": "module",
  "exports": {
    ".": "./dist/index.js"
  }
}

The user installs it:

npm install my-library

Then runs:

import { hello } from 'my-library'

console.log(hello('Tom'))

Here, my-library is a package name, rather than a file path. Node.js must first answer:

Which file on disk corresponds to this package name?

3.2 How Does Node.js Find npm Packages?

In a typical Node.js project, npm installs dependencies into node_modules:

my-app/
├── package.json
├── index.js
└── node_modules/
    └── my-library/
        ├── package.json
        └── dist/
            └── index.js

When Node.js encounters:

import { hello } from 'my-library'

It searches for the package according to its module resolution rules.

For ordinary bare package imports, Node.js starts with node_modules directories near the importing file and continues through parent directories as specified by those rules.

Once it locates the package, it reads the relevant package.json metadata to determine the actual module entry point.

Node.js uses different resolution algorithms for ESM and CommonJS; this describes the overall process for clarity.

3.3 How Do exports and main Differ?

Older npm packages commonly declare an entry point through main:

{
  "main": "./dist/index.js"
}

As ESM has become more widely used, modern packages increasingly use exports:

{
  "exports": {
    ".": "./dist/index.js",
    "./utils": "./dist/utils.js"
  }
}

This allows users to import:

import { hello } from 'my-library'
import { format } from 'my-library/utils'

Besides declaring the main entry, exports specifies which subpaths are publicly accessible.

When exports is configured, Node.js generally prevents access to undeclared internal subpaths through the package name. For example:

import something from 'my-library/internal.js'

This may fail even if the file exists, because the path has not been exposed through exports.

The exports field therefore also defines the boundary of the package’s public API.

3.4 ESM and CommonJS

Two module systems have long coexisted in the JavaScript ecosystem.

CommonJS:

const lodash = require('lodash')

module.exports = {
  hello
}

ES Modules (ESM):

import lodash from 'lodash'

export function hello() {}

In Node.js, the .mjs and .cjs extensions, along with the type field in package.json, affect how module format is determined.

For example:

{
  "type": "module"
}

This tells Node.js to interpret ordinary .js files within the package scope as ESM.

To offer entry points for both ESM and CommonJS users, we can configure conditional exports:

{
  "exports": {
    ".": {
      "import": "./dist/index.js",
      "require": "./dist/index.cjs"
    }
  }
}

Here:

Both entries must contain code compatible with the corresponding module system. Changing file extensions alone is not enough.

3.5 How Does a Library Manage Its Own Dependencies?

Suppose my-library uses Lodash internally. We can declare:

{
  "dependencies": {
    "lodash": "^4.17.21"
  }
}

When a user installs my-library, the package manager installs dependencies that satisfy its declarations.

A package can therefore be a direct dependency of one project and a transitive dependency of another. The underlying package is the same; its position in the dependency tree differs.

Several related package.json fields are easy to confuse:

FieldPurpose
dependenciesRegular dependencies needed at runtime
devDependenciesDependencies used for development, testing, and building
peerDependenciesCompatible dependencies that need coordination with the consuming environment
optionalDependenciesOptional dependencies whose installation failures can be tolerated

React component libraries commonly declare React as a peer dependency to avoid requiring a separate React instance from the host application.

TypeScript, test frameworks, and build tools usually belong in devDependencies.

Crucially, devDependencies are not installed into consumer projects as ordinary transitive dependencies of the published package.

If the published JavaScript still needs a package at runtime, we should not place it in devDependencies simply because it happens to be available in our development environment.

We can now outline how a library is used:

User runs npm install
       │
       ▼
Package manager resolves and installs dependencies
       │
       ▼
Package files become available to the project
       │
       ▼
Code executes import
       │
       ▼
Node.js / build tool resolves package name
       │
       ▼
Reads entry declarations in package.json
       │
       ▼
Loads the corresponding module

Next, we can discuss turning source code into a package that is ready to publish.


4. How Do You Build and Publish a CLI Package?

We know the most important CLI configuration is its bin entry. In practice, though, we rarely write all our JavaScript directly in bin/cli.js.

With TypeScript in particular, we usually build the code first and publish the resulting artifacts.

We need to distinguish three stages:

  1. Build: transform source code into runnable JavaScript.
  2. Pack: select the files to distribute and create an npm package archive.
  3. Publish: upload the package to the npm Registry.

These are separate operations.

4.1 Creating a TypeScript CLI Project

Suppose we are developing a command-line tool called my-cli.

Project structure:

my-cli/
├── src/
│   └── cli.ts
├── package.json
└── tsconfig.json

src/cli.ts:

#!/usr/bin/env node

const name = process.argv[2] ?? 'World'

console.log(`Hello, ${name}!`)

The shebang must remain on the first line of the final executable file.

We can use the TypeScript compiler to turn the source into JavaScript. For example:

npm install -D typescript

Configure tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "rootDir": "src",
    "outDir": "dist",
    "strict": true
  },
  "include": ["src"]
}

Then configure package.json:

{
  "name": "my-cli",
  "version": "1.0.0",
  "type": "module",
  "bin": {
    "my-cli": "./dist/cli.js"
  },
  "scripts": {
    "build": "tsc"
  },
  "files": [
    "dist"
  ],
  "devDependencies": {
    "typescript": "^5.0.0"
  }
}

Other metadata needed for an actual publication is omitted here and should be added for the specific project.

Run:

npm run build

This produces:

my-cli/
├── src/
│   └── cli.ts
├── dist/
│   └── cli.js
├── package.json
└── tsconfig.json

Remember: the TypeScript compiler generates JavaScript; it does not automatically publish the package to npm.

Also check that dist/cli.js retains its shebang and has the permissions needed for CLI execution.

4.2 What Does the files Field Do?

Our earlier configuration included:

{
  "files": ["dist"]
}

This field primarily controls which files npm includes when packing. It is separate from the mechanism that executes a CLI.

For example, our project might contain:

my-cli/
├── src/
├── dist/
├── tests/
├── README.md
├── package.json
└── tsconfig.json

But users typically only need:

package/
├── dist/
├── README.md
└── package.json

The files field acts as an allowlist for distribution.

npm also has default inclusion and exclusion rules. Files such as package.json and README may be included automatically, and bin entry files receive special handling.

We therefore cannot assume that every file omitted from files will be excluded from publication.

The most reliable approach is to inspect the actual packed output.

4.3 What Does npm pack Do?

Run:

npm pack --dry-run

This previews the files npm plans to pack.

Running:

npm pack

Creates a local .tgz archive, for example:

my-cli-1.0.0.tgz

This is the archive format used to distribute npm packages.

npm publishes the files selected by its packing rules, rather than your entire Git repository.

That explains why code can work locally but fail for users after publication with:

Cannot find module

A required file may have been left out of the final package.

Before publishing, inspect the output of npm pack. If necessary, install the .tgz into a clean test project to verify it.

4.4 Publishing the Package

First, create an npm account and complete the authentication required by the npm CLI you are using.

Then run:

npm publish

For a public scoped package, such as:

@my-scope/my-cli

The first publication can usually use:

npm publish --access public

The applicable authentication and permission requirements depend on the current npm Registry rules.

Once published, users can run the tool with:

npx my-cli

To publish a new version, first update the version in package.json:

npm version patch

Then rebuild, inspect, and publish.

An important point: once an npm package’s name + version combination has been published, you cannot simply overwrite it.

Version management is therefore an essential part of maintaining a package.


5. How Do You Build and Publish a Library?

Building a library involves more considerations than building a CLI.

CLI authors can usually decide their primary execution environment, while a library must be loaded by other projects.

Consumers might use:

We need to generate runnable JavaScript and clearly describe how consumers should load it.

5.1 Creating a TypeScript Library

Suppose we are developing a utility library called my-library.

Project structure:

my-library/
├── src/
│   └── index.ts
├── package.json
└── tsconfig.json

src/index.ts:

export function hello(name: string): string {
  return `Hello, ${name}!`
}

export function add(a: number, b: number): number {
  return a + b
}

We want consumers to write:

import { hello, add } from 'my-library'

There are three aspects to consider:

  1. JavaScript module files
  2. Module format: ESM or CommonJS
  3. TypeScript type declarations

5.2 Building with tsup

For a simple TypeScript utility library, we can use tsup:

npm install -D tsup typescript

Configure:

{
  "scripts": {
    "build": "tsup src/index.ts --format esm,cjs --dts --clean"
  }
}

Then run:

npm run build

Depending on the tsup version and configuration, the output typically looks like:

dist/
├── index.js
├── index.cjs
├── index.d.ts
└── index.d.cts

Here:

Always check the actual filenames produced by the build.

A library targeting only modern ESM environments can publish ESM alone; dual-format output is not always necessary.

5.3 Configuring Module Entry Points

To support both ESM and CommonJS, we can configure:

{
  "name": "my-library",
  "version": "1.0.0",
  "type": "module",
  "main": "./dist/index.cjs",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "import": {
        "types": "./dist/index.d.ts",
        "default": "./dist/index.js"
      },
      "require": {
        "types": "./dist/index.d.cts",
        "default": "./dist/index.cjs"
      }
    }
  },
  "files": ["dist"],
  "scripts": {
    "build": "tsup src/index.ts --format esm,cjs --dts --clean"
  }
}

The key field is exports. It declares JavaScript entry points and distinguishes loading methods through conditional exports.

The types entries provide type information to TypeScript tooling. The top-level types field can also support some older tools.

Publishing both formats involves more than generating two files. Both module entries and their declarations need to work correctly.

5.4 Why Does a Library Need Type Declarations?

JavaScript does not need TypeScript types at runtime. For example:

export function add(a, b) {
  return a + b
}

This code runs normally.

For TypeScript users, however, we want the editor to understand:

add(a: number, b: number): number

That is where .d.ts files come in. For example:

export declare function add(
  a: number,
  b: number
): number

Building a TypeScript library therefore typically involves generating and distributing type information alongside the JavaScript output.

This is an important practical difference between a CLI and a library.

A CLI generally needs to ensure its command can execute. A library must also make its public API understandable to different module systems and development tools.


Conclusion

Returning to the original question: what do you need to know before publishing an npm package?

I think the most important thing is understanding the package’s complete lifecycle, from development to use, rather than memorizing a collection of package.json fields.

First, an npm package is a unit of code distribution. It can expose library APIs for other programs, CLI commands for users, or both.

These two interfaces operate differently.

For a CLI, the package manager creates command entries from bin, and the execution environment launches the program through PATH, a shebang, or a platform-specific command wrapper. npx adds the ability to prepare and execute packages on demand.

For a library, the package manager installs dependencies, and Node.js or a build tool resolves the code using module resolution rules and the entry declarations in package.json.

Finally, both kinds of package involve three distinct stages:

Build → Pack → Publish

Building determines the form in which the code runs. Packing determines which files users receive. Publishing distributes those files through the npm Registry.

Once we understand these mechanisms, fields such as bin, exports, dependencies, and files stop looking like isolated configuration options. Together, they describe how a package is installed, loaded, executed, and distributed.

That is the understanding we need to publish an npm package.