Manager and filter for .gitignore rules, providing comprehensive gitignore-style pattern matching for file filtering.
npx @tessl/cli install tessl/npm-ignore@7.0.0Ignore is a manager, filter and parser for .gitignore rules implemented in pure JavaScript according to the .gitignore specification 2.22.1. It provides comprehensive gitignore-style pattern matching for file filtering and is widely used by tools like ESLint, Gitbook, and many others.
npm install ignoreimport ignore from 'ignore';For CommonJS:
const ignore = require('ignore');For TypeScript with named imports:
import ignore, { isPathValid } from 'ignore';Named import for the main function (alternative syntax):
import { default as ignore, isPathValid } from 'ignore';import ignore from 'ignore';
// Create an ignore instance
const ig = ignore().add(['.abc/*', '!.abc/d/']);
// Test individual paths
console.log(ig.ignores('.abc/a.js')); // true (ignored)
console.log(ig.ignores('.abc/d/e.js')); // false (not ignored due to negation)
// Filter arrays of paths
const paths = ['.abc/a.js', '.abc/d/e.js', 'other.js'];
const filtered = ig.filter(paths);
console.log(filtered); // ['.abc/d/e.js', 'other.js']
// Use as filter function
const nonIgnored = paths.filter(ig.createFilter());The ignore package is built around several key components:
ignore() function creates new Ignore instances with optional configurationCreates new ignore manager instances with optional configuration.
/**
* Creates a new ignore manager instance
* @param options - Configuration options for the ignore instance
* @returns Ignore instance for managing gitignore rules
*/
function ignore(options?: Options): Ignore;
/**
* Legacy compatibility property (anti-pattern)
* @deprecated Use ignore() directly instead
*/
ignore.default: typeof ignore;
interface Options {
/** Case insensitive matching (default: true) */
ignorecase?: boolean;
/** Alternative name for ignorecase */
ignoreCase?: boolean;
/** Allow relative paths like './foo' (default: false) */
allowRelativePaths?: boolean;
}Usage Examples:
// Default case-insensitive behavior
const ig1 = ignore();
// Case-sensitive matching
const ig2 = ignore({ ignorecase: false });
// Allow relative paths (not recommended)
const ig3 = ignore({ allowRelativePaths: true });Add ignore patterns to the manager using various input formats.
/**
* Adds one or several rules to the current manager
* @param patterns - Pattern(s) to add - can be strings, arrays, or other ignore instances
* @returns The ignore instance for chaining
*/
add(patterns: string | Ignore | readonly (string | Ignore)[] | PatternParams): this;
/**
* Legacy alias for add method
* @param pattern - Pattern to add
* @returns The ignore instance for chaining
*/
addPattern(pattern: string | Ignore | readonly (string | Ignore)[]): this;
interface PatternParams {
/** The ignore pattern string */
pattern: string;
/** Optional marker for pattern tracking (e.g., line number) */
mark?: string;
}Usage Examples:
// Add single pattern
ig.add('*.log');
// Add multiple patterns
ig.add(['*.log', 'temp/', '!important.log']);
// Add from file content
ig.add(fs.readFileSync('.gitignore', 'utf8'));
// Add with marker for debugging
ig.add({ pattern: 'debug/*', mark: 'line:15' });
// Add another ignore instance
const baseIgnore = ignore().add('*.tmp');
ig.add(baseIgnore);
// Legacy addPattern method (use add() instead)
ig.addPattern('*.log');
ig.addPattern(['*.log', 'temp/']);
// Chaining
const ig = ignore()
.add('*.log')
.add('temp/')
.add('!important.log');Test individual paths against ignore rules with detailed results.
/**
* Tests if a pathname should be ignored
* @param pathname - Relative path to test
* @returns Boolean indicating if path is ignored
*/
ignores(pathname: Pathname): boolean;
/**
* Tests path and returns detailed result including rule information
* @param pathname - Relative path to test
* @returns TestResult with ignored/unignored status and matching rule
*/
test(pathname: Pathname): TestResult;
/**
* Git check-ignore equivalent debugging method
* @param pathname - Relative path to test
* @returns TestResult for debugging ignore rules
*/
checkIgnore(pathname: Pathname): TestResult;
type Pathname = string;
interface TestResult {
/** Whether path is ignored */
ignored: boolean;
/** Whether path is unignored by negative pattern */
unignored: boolean;
/** The rule that matched (if any) */
rule?: IgnoreRule;
}
interface IgnoreRule {
/** Original pattern string */
pattern: string;
/** Optional marker (e.g., line number) */
mark?: string;
/** Whether this is a negation pattern */
negative: boolean;
}Usage Examples:
const ig = ignore().add(['*.log', '!important.log']);
// Simple boolean test
console.log(ig.ignores('debug.log')); // true
console.log(ig.ignores('important.log')); // false
// Detailed test result
const result = ig.test('debug.log');
console.log(result.ignored); // true
console.log(result.unignored); // false
console.log(result.rule); // { pattern: '*.log', negative: false }
// Check ignore for debugging (like git check-ignore -v)
const debugResult = ig.checkIgnore('temp/');
if (debugResult.ignored) {
console.log(`Ignored by rule: ${debugResult.rule.pattern}`);
}Filter arrays of paths to remove ignored entries.
/**
* Filters array of pathnames, removing ignored paths
* @param pathnames - Array of relative paths to filter
* @returns Filtered array containing only non-ignored paths
*/
filter(pathnames: readonly Pathname[]): Pathname[];
/**
* Creates filter function for use with Array.prototype.filter
* @returns Filter function that returns true for non-ignored paths
*/
createFilter(): (pathname: Pathname) => boolean;Usage Examples:
const ig = ignore().add(['*.log', 'temp/', '!important.log']);
const allFiles = [
'app.js',
'debug.log',
'important.log',
'temp/cache.tmp',
'src/index.js'
];
// Direct filtering
const kept = ig.filter(allFiles);
console.log(kept); // ['app.js', 'important.log', 'src/index.js']
// Using createFilter with Array methods
const filterFn = ig.createFilter();
const keptFiles = allFiles.filter(filterFn);
// Chaining with other array methods
const jsFiles = allFiles
.filter(ig.createFilter())
.filter(file => file.endsWith('.js'));Utility function to validate pathname format according to ignore conventions.
/**
* Validates if pathname is a proper relative path according to ignore conventions
* @param pathname - Path string to validate
* @returns Boolean indicating if path format is valid
*/
function isPathValid(pathname: string): boolean;Usage Examples:
import { isPathValid } from 'ignore';
console.log(isPathValid('src/app.js')); // true
console.log(isPathValid('./src/app.js')); // false (relative prefix not allowed)
console.log(isPathValid('/src/app.js')); // false (absolute path not allowed)
console.log(isPathValid('')); // false (empty string not allowed)
// Validate before processing
const paths = ['src/app.js', './config.js', '/tmp/file.txt']
.filter(isPathValid);
// Result: ['src/app.js']The ignore package throws errors for invalid inputs:
./, ../, or is absolute)const ig = ignore();
try {
ig.ignores('/absolute/path'); // Throws RangeError
} catch (error) {
console.error(error.message); // "path should be a `path.relative()`d string"
}
try {
ig.ignores(''); // Throws TypeError
} catch (error) {
console.error(error.message); // "path must not be empty"
}The ignore package follows the official .gitignore specification:
const ig = ignore().add([
// Basic patterns
'*.log', // All .log files
'temp/', // Directory temp/ and contents
'/config', // Only config in root
// Wildcards
'cache/*', // Files directly in cache/
'cache/**', // All files under cache/ recursively
'cache/**/debug', // debug files anywhere under cache/
// Negation
'!important.log', // Don't ignore important.log
'*.tmp', // Ignore .tmp files
'!cache/*.tmp', // But keep .tmp files in cache/
// Character ranges
'temp[0-9].txt', // temp0.txt through temp9.txt
// Escaping
'\\#notes.txt', // Literal # character
'\\ spaced\\ file', // File with spaces
]);The package automatically handles Windows paths:
const ig = ignore().add('temp/*');
// These are equivalent on Windows:
ig.ignores('temp/file.txt'); // true
ig.ignores('temp\\file.txt'); // true (automatically converted)Configure case sensitivity based on filesystem:
// Case insensitive (default - good for Windows/macOS)
const ig1 = ignore().add('*.TXT');
console.log(ig1.ignores('file.txt')); // true
// Case sensitive (good for Linux)
const ig2 = ignore({ ignorecase: false }).add('*.TXT');
console.log(ig2.ignores('file.txt')); // false
console.log(ig2.ignores('file.TXT')); // truecreateFilter() when filtering the same paths multiple timescheckIgnore() method has weaker caching and should be used only for debuggingtype Pathname = string;
interface Options {
ignorecase?: boolean;
ignoreCase?: boolean;
allowRelativePaths?: boolean;
}
interface TestResult {
ignored: boolean;
unignored: boolean;
rule?: IgnoreRule;
}
interface IgnoreRule {
pattern: string;
mark?: string;
negative: boolean;
}
interface PatternParams {
pattern: string;
mark?: string;
}
interface Ignore {
add(patterns: string | Ignore | readonly (string | Ignore)[] | PatternParams): this;
addPattern(pattern: string | Ignore | readonly (string | Ignore)[]): this;
ignores(pathname: Pathname): boolean;
test(pathname: Pathname): TestResult;
checkIgnore(pathname: Pathname): TestResult;
filter(pathnames: readonly Pathname[]): Pathname[];
createFilter(): (pathname: Pathname) => boolean;
}