Sub topic 12
Packaging and running the command
This chapter turns the compiled dist/cli.js into a command named wcl that you can run from any directory. It assumes you have the project from the earlier chapters: a TypeScript source tree in src, a tsconfig.json that emits to dist, and a src/cli.ts entry file that starts with a shebang line. You should know basic terminal use and what package.json fields do.
How a command gets onto your PATH
A command-line tool is a file the shell can find and execute. The shell searches each directory in the PATH environment variable for a file with the typed name. npm's job is to put a link to your script in one of those directories.
The bin field in package.json tells npm which file to link and what name to give it. When you install a package globally, or run npm link, npm creates a symlink in its global bin directory. That symlink points to the file you named.
Three things must be true for this chain to work:
- The target file exists, which means you have run the build.
- The target file starts with a valid shebang line.
- The target file is executable. npm sets the executable bit on
bintargets when it links or installs them, so you don't runchmodyourself.
The package.json for a distributable tool
Here is the finished package.json for wcl. It extends the version from earlier chapters with an engines field and a prepare script.
{
"name": "wcl",
"version": "1.0.0",
"description": "Count lines and words in a file",
"type": "module",
"bin": { "wcl": "dist/cli.js" },
"files": ["dist"],
"engines": { "node": ">=20" },
"scripts": {
"build": "tsc",
"test": "tsc && node --test dist",
"prepare": "npm run build"
},
"devDependencies": {
"@types/node": "^20.0.0",
"typescript": "^5.4.0"
}
}Each field has a job:
| Field | Purpose |
|---|---|
| `type` | `"module"` makes Node treat `.js` files as ES modules. The compiled output uses `import` and top-level `await`, so it needs this. |
| `bin` | Maps the command name `wcl` to the file `dist/cli.js`. |
| `files` | Lists what goes into the published tarball. Everything else is left out. |
| `engines` | Documents the Node versions the tool supports. npm warns on a mismatch, and it blocks the install only if `engine-strict` is set. |
| `prepare` | Runs before the package is packed or published, and after a plain `npm install` in the project directory. It keeps `dist` from going stale. |
You can also write bin as a plain string, "bin": "dist/cli.js". npm then uses the package name as the command name. The object form is clearer, and it lets you expose several commands from one package.
The shebang line must survive compilation
The first line of src/cli.ts is #!/usr/bin/env node. When the shell runs wcl, the operating system reads that line and starts node with the script as its argument. Using env finds node on your PATH instead of hard-coding its location.
TypeScript recognizes a leading shebang and copies it unchanged to the first line of the output. Check this after your first build:
npm run build
head -n 1 dist/cli.jsThe output should be:
#!/usr/bin/env nodeIf the line is missing or something else comes before it, the shell will try to interpret the JavaScript as shell commands and print confusing errors. Two common causes are a comment or blank line placed above the shebang in the source, and a build step that adds a banner to the output. The shebang must be the very first bytes of the file.
Linking the command locally
npm link is the quickest way to try your command while you are still developing it. Run it from the project root:
npm run build
npm linknpm creates a link from its global node_modules directory to your project folder. It also creates the wcl symlink in the global bin directory. Then check where the shell finds the command:
which wcl
wcl --versionOn Windows, use where wcl instead of which. npm creates .cmd and PowerShell wrapper files there, since Windows ignores shebangs.
Now run the tool on a real file from a different directory, to prove it no longer depends on your project folder:
cd /tmp
printf 'a b\nc\n' > notes.txt
wcl notes.txt
echo "exit code: $?"
wcl missing.txt
echo "exit code: $?"Expected output:
2 3 notes.txt
exit code: 0
wcl: missing.txt: no such file
exit code: 1The first run prints lines, words, and the file name, and exits with 0. The second run prints the message on stderr and exits with 1. Both match the exit-code design from the error handling chapter, and this is where it pays off: other programs and shell scripts can now branch on $? or &&.
Because the link points at your project, rebuilding updates the command at once. You can edit src/cli.ts, run npm run build, and call wcl again without relinking. The link is a symlink, so it never holds a copy of your code.
To remove it, run npm unlink -g wcl. Run it from any directory.
Checking what will be published
A package is shipped as a tarball. Before you publish, or hand the tool to a colleague, inspect what the tarball contains without creating it:
npm pack --dry-runnpm lists each file and the total size. With "files": ["dist"], you should see package.json, dist/cli.js, dist/count.js, and any other compiled output. npm always includes package.json, plus the README and LICENSE files if they exist, whatever files says.
Look at the list for two kinds of surprises.
Compiled test files. Because tsc compiles everything under src, a test file such as src/count.test.ts becomes dist/count.test.js and ships to users. It does no harm, but it adds weight, and users never need it. You can exclude test files with a negated pattern in files:
{
"files": ["dist", "!dist/**/*.test.js"]
}A cleaner long-term option is to put tests in a separate directory with their own tsconfig. For a small tool, the negated pattern is enough.
Missing files. If dist is not in the list, you forgot to build. This is why the prepare script exists: npm runs it before packing, so dist is created first. Without it, a fresh clone has no dist directory, and the package is broken.
Installing from the tarball
npm link shares your working folder. A real install copies the files, and that exposes mistakes link hides, such as a file you forgot to include. To test the real path, create a tarball and install it globally:
npm pack
npm install -g ./wcl-1.0.0.tgz
wcl notes.txtWhen this works, the tool is self-contained. If you see Cannot find module, a file is missing from files, or the tool imports a runtime package you listed under devDependencies instead of dependencies. wcl has no runtime dependencies yet, because parseArgs and fs/promises ship with Node. Anything the compiled code imports at runtime must go in dependencies. TypeScript and @types/node are only needed at build time, so devDependencies is correct for them.
Remove the test install with npm uninstall -g wcl.
Running without installing
Two other ways to run the tool are useful during development and in scripts.
Run the compiled file directly with Node. This ignores the shebang and the executable bit:
node dist/cli.js notes.txtOr run the package's own bin through npm from inside the project:
npx wcl notes.txtInside a project that declares a bin, npx runs the local command. When the package is published, anyone can run it with npx wcl notes.txt without installing it first. npm downloads it to a cache and runs it.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `command not found: wcl` | The link was never made, or the global `bin` directory is not on `PATH`. | Run `npm link` again. Find the directory with `npm prefix -g` and add its `bin` subfolder to `PATH`. |
| `permission denied` | The target file is not executable, which can happen if the file was copied by hand. | Reinstall or relink so npm sets the bit, or run `chmod +x dist/cli.js`. |
| `env: node\r: No such file or directory` | The file has Windows line endings (CRLF), so the interpreter name includes a carriage return. | Convert the source to LF line endings. Add `* text=auto eol=lf` to `.gitattributes`. |
| `SyntaxError: Cannot use import statement outside a module` | `"type": "module"` is missing from `package.json`. | Add it, and make sure `tsconfig.json` uses `"module": "NodeNext"`. |
| Command runs old behavior | You edited the source but did not rebuild. | Run `npm run build`. |
| `Cannot find module '.../count'` | An import in the source is missing its `.js` extension, which NodeNext requires. | Write `import { countText } from "./count.js"` in the TypeScript source. |
Exercise
Exercise
You run npm link, and wcl notes.txt fails with "permission denied". ls -l dist/cli.js shows the file exists. Name two checks you would make, and say why editing src/cli.ts and rebuilding would not by itself explain the error.
Show answer
First, check that which wcl points to a symlink whose target is your project's dist/cli.js, and check the file's mode with ls -l. If the executable bit is missing, run npm link again or chmod +x dist/cli.js. Second, check that the first line of dist/cli.js is exactly #!/usr/bin/env node with no CRLF line ending, using head -n 1 dist/cli.js. Rebuilding with tsc rewrites the file contents but does not manage permissions or fix a bad line ending in the source, so a rebuild alone does not explain or fix a "permission denied" error. Relinking makes npm set the executable bit again.
Exercise
A teammate installs your tarball and gets Cannot find module 'chalk'. You added chalk to devDependencies. What went wrong, and how do you fix it?
Show answer
Packages in devDependencies are not installed for users of the published package. Code that imports chalk at runtime needs it under dependencies. Move it with npm install chalk (without --save-dev), rebuild, and test again with npm pack and a global install of the tarball.