or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-npm-packlist

Get a list of the files to add from a folder into an npm package

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/npm-packlist@10.0.x

To install, run

npx @tessl/cli install tessl/npm-npm-packlist@10.0.0

index.mddocs/

npm-packlist

npm-packlist analyzes npm package directories to determine which files should be included when creating package tarballs. It implements npm's file inclusion and exclusion rules by analyzing package.json files lists, .npmignore files, .gitignore files, and applying default exclusion patterns.

Package Information

  • Package Name: npm-packlist
  • Package Type: npm
  • Language: JavaScript (Node.js)
  • Installation: npm install npm-packlist

Core Imports

const packlist = require('npm-packlist');
const { Walker } = require('npm-packlist');

ES modules (if supported by environment):

import packlist, { Walker } from 'npm-packlist';

Basic Usage

npm-packlist requires an Arborist tree object representing the package structure:

const Arborist = require('@npmcli/arborist');
const packlist = require('npm-packlist');

// Load package tree
const arborist = new Arborist({ path: '/path/to/package' });
const tree = await arborist.loadActual();

// Get list of files to include in package
const files = await packlist(tree);
console.log(files); // Array of file paths relative to package root

// Use with tar to create package
const tar = require('tar');
tar.create({
  prefix: 'package/',
  cwd: '/path/to/package',
  file: '/path/to/package.tgz',
  gzip: true
}, files);

Architecture

npm-packlist is built around several key components:

  • PackWalker Class: Extends ignore-walk's Walker to implement npm-specific file inclusion rules
  • Rule System: Uses synthetic rule sets (defaultRules, strictRules) and file-based rules (.npmignore, .gitignore, package.json)
  • Bundle Support: Handles bundled dependencies by recursively walking their file trees
  • Workspace Integration: Supports npm workspaces and monorepo structures
  • Ignore Precedence: Implements npm's ignore file precedence order

Capabilities

Package File Discovery

Main function that walks a package tree and returns files to include in the npm package tarball.

/**
 * Walk a package tree and return list of files to include
 * @param {Object} tree - Arborist tree object representing the package
 * @param {Object} [options] - Configuration options
 * @param {Function} [callback] - Optional callback for callback-style usage
 * @returns {Promise<string[]>} Array of file paths relative to package root
 */
function packlist(tree, options, callback);

Usage Examples:

const Arborist = require('@npmcli/arborist');
const packlist = require('npm-packlist');

// Promise-based usage
const arborist = new Arborist({ path: './my-package' });
const tree = await arborist.loadActual();
const files = await packlist(tree);

// With options
const files = await packlist(tree, {
  ignoreFiles: ['.npmignore', '.gitignore'],
  requiredFiles: ['README.md', 'CHANGELOG.md']
});

// Callback-based usage
packlist(tree, (err, files) => {
  if (err) throw err;
  console.log('Files to include:', files);
});

Advanced Walker Interface

Direct access to the PackWalker class for advanced use cases and custom configurations.

/**
 * PackWalker class for advanced package file walking
 * Extends ignore-walk's Walker with npm-specific behavior
 */
class Walker extends IgnoreWalker {
  /**
   * Create a new PackWalker instance
   * @param {Object} tree - Arborist tree object
   * @param {Object} opts - Walker options
   */
  constructor(tree, opts);
}

Walker Options:

interface WalkerOptions {
  /** Path to walk (defaults to tree.path) */
  path?: string;
  /** Whether this walker represents a package root */
  isPackage?: boolean;
  /** Array of ignore file names to respect */
  ignoreFiles?: string[];
  /** Files that must be included regardless of ignore rules */
  requiredFiles?: string[];
  /** Set of already seen nodes (for circular dependency prevention) */
  seen?: Set<Object>;
  /** Workspace root prefix path */
  prefix?: string;
  /** Array of workspace directory paths */
  workspaces?: string[];
}

Usage Examples:

const { Walker } = require('npm-packlist');
const Arborist = require('@npmcli/arborist');

// Create custom walker
const arborist = new Arborist({ path: './my-package' });
const tree = await arborist.loadActual();

const walker = new Walker(tree, {
  isPackage: true,
  ignoreFiles: ['.mynpmignore', '.gitignore'],
  requiredFiles: ['important-file.txt']
});

// Use event-driven interface
const files = await new Promise((resolve, reject) => {
  walker
    .on('done', resolve)
    .on('error', reject)
    .start();
});

File Inclusion Rules

npm-packlist implements npm's file inclusion rules in the following precedence order:

  1. package.json files array: If present, only include files listed (plus required files)
  2. .npmignore: If no files array, use .npmignore rules
  3. .gitignore: If no files array or .npmignore, use .gitignore rules
  4. Default exclusions: Always exclude common cruft files unless explicitly included

Always Included Files:

  • package.json (root only)
  • README files (readme, readme., copying, copying., license, license., licence, licence.)
  • Files specified in package.json main, browser, and bin fields

Always Excluded Files:

  • .git directories and contents
  • node_modules (unless bundled dependencies)
  • .DS_Store files
  • Editor temporary files (.swp, ._, *.orig)
  • .npmrc files
  • Lock files (package-lock.json, yarn.lock, pnpm-lock.yaml, bun.lockb)

Bundled Dependencies

Automatic handling of bundled dependencies specified in package.json.

/**
 * Bundled dependency handling is automatic when using packlist()
 * Dependencies listed in bundleDependencies are included with their files
 * For non-root packages, all production and optional dependencies are bundled
 */

The walker automatically:

  • Identifies bundled dependencies from package.json
  • Recursively walks bundled dependency file trees
  • Applies appropriate ignore rules for linked vs regular dependencies
  • Prevents infinite loops in circular dependency graphs

Workspace Support

Built-in support for npm workspaces and monorepo structures.

/**
 * Workspace support is automatic when workspace information is present in the tree
 * Use workspace-specific options for custom behavior
 */
interface WorkspaceOptions {
  /** Root directory of the workspace */
  prefix: string;
  /** Array of workspace directory paths */
  workspaces: string[];
}

Usage Examples:

// Workspace support is automatic with Arborist
const arborist = new Arborist({ 
  path: '/workspace/root',
  workspaces: ['packages/*']
});
const tree = await arborist.loadActual();

// Package files for workspace root
const rootFiles = await packlist(tree);

// Package files for specific workspace
const workspaceArborist = new Arborist({ path: '/workspace/root/packages/my-package' });
const workspaceTree = await workspaceArborist.loadActual();
const workspaceFiles = await packlist(workspaceTree);

Types

/**
 * Main packlist function signature
 */
declare function packlist(
  tree: ArboristNode,
  options?: PacklistOptions,
  callback?: (err: Error | null, files: string[]) => void
): Promise<string[]>;

/**
 * Arborist tree node (simplified interface)
 */
interface ArboristNode {
  path: string;
  package: {
    name?: string;
    version?: string;
    files?: string[];
    main?: string;
    browser?: string;
    bin?: { [key: string]: string } | string;
    bundleDependencies?: string[];
    dependencies?: { [key: string]: string };
    optionalDependencies?: { [key: string]: string };
  };
  isProjectRoot: boolean;
  workspaces?: Map<string, string>;
  edgesOut?: Map<string, Edge>;
}

/**
 * Arborist edge (dependency link)
 */
interface Edge {
  to: ArboristNode;
  peer: boolean;
  dev: boolean;
}

/**
 * Configuration options for packlist
 */
interface PacklistOptions {
  /** Path to walk (overrides tree.path) */
  path?: string;
  /** Array of ignore file names to respect */
  ignoreFiles?: string[];
  /** Files that must be included regardless of ignore rules */
  requiredFiles?: string[];
  /** Workspace root prefix path */
  prefix?: string;
  /** Array of workspace directory paths */
  workspaces?: string[];
}

Error Handling

npm-packlist handles several error conditions gracefully:

  • Missing files: Files listed in package.json files array that don't exist are silently skipped
  • Permission errors: File system permission errors are propagated as exceptions
  • Invalid trees: Missing or malformed Arborist tree objects throw errors
  • Circular dependencies: Prevented using seen node tracking

Common Error Patterns:

try {
  const files = await packlist(tree);
} catch (error) {
  if (error.code === 'ENOENT') {
    console.error('Package directory not found');
  } else if (error.code === 'EACCES') {
    console.error('Permission denied reading package files');
  } else {
    console.error('Unexpected error:', error.message);
  }
}