Get a list of the files to add from a folder into an npm package
npx @tessl/cli install tessl/npm-npm-packlist@10.0.0npm-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.
npm install npm-packlistconst packlist = require('npm-packlist');
const { Walker } = require('npm-packlist');ES modules (if supported by environment):
import packlist, { Walker } from 'npm-packlist';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);npm-packlist is built around several key components:
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);
});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();
});npm-packlist implements npm's file inclusion rules in the following precedence order:
Always Included Files:
Always Excluded Files:
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:
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);/**
* 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[];
}npm-packlist handles several error conditions gracefully:
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);
}
}