npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

barrel-craft

v0.1.0

Published

Generate clean and consistent barrels (index.ts and index.tsx files) for your TypeScript and React projects with a single command

Readme

🛢️ Barrel Craft

A powerful CLI tool for generating clean and consistent barrel files (index.ts and index.tsx) for your TypeScript and React projects.

🚀 What is Barrel Craft?

Barrel Craft automates the creation of barrel files (index exports) that help organize and simplify imports in TypeScript and React projects. Instead of importing files individually from deep nested paths, barrel files allow you to import multiple modules from a single entry point.

Before:

import { UserService } from "./services/user/UserService";
import { AuthService } from "./services/auth/AuthService";
import { Button } from "./components/ui/Button";
import { Modal } from "./components/ui/Modal";

After:

import { UserService, AuthService } from "./services";
import { Button, Modal } from "./components/ui";

✨ Features

  • 🔍 Smart Discovery: Automatically finds and processes TypeScript/React files
  • 📁 Flexible Configuration: Support for config files with advanced patterns
  • 🎯 Pattern Matching: Exclude test files, specs, and other unwanted files
  • 📱 Extension Smart: Automatically uses .tsx when JSX files are present
  • 🌳 Subdirectory Support: Process nested directories recursively
  • 🔧 Force Generation: Create barrels even for empty directories with valid subdirectories
  • 🔇 Quiet Mode: Clean, minimal output by default with optional verbose mode
  • Safe: Never overwrites existing index.tsx when generating index.ts

📦 Installation

Global Installation (Recommended)

npm install -g barrel-craft

Local Installation

npm install --save-dev barrel-craft

🎯 Usage

Quick Start

# Generate barrel for current directory
barrel-craft
# or use shorter aliases:
barrel
craft

# Generate barrel for specific directory
barrel-craft ./src/components

# Include subdirectories (or use config file with subdirectories: true)
barrel-craft ./src --subdirectories

# Show detailed output
barrel-craft ./src -V
# or
barrel-craft ./src --verbose

Configuration File

Create a configuration file for advanced usage:

barrel-craft init

This creates a barrel-craft.json file:

{
  "headerComment": "// Auto-generated by barrel-craft\n\n",
  "targets": ["src"],
  "forceGenerate": [],
  "exclude": ["**/*.test.*", "**/*.spec.*", "**/*.d.ts"],
  "extensions": ["ts", "tsx"],
  "sortExports": true,
  "subdirectories": true,
  "verbose": false,
  "force": false
}

CLI Options

barrel-craft [directory] [options]

Options:
  -v, --version                     Output the version number
  -e, --extensions <extensions...>  File extensions to include (default: ["ts","tsx"])
  -x, --exclude <patterns...>       Patterns to exclude (default: ["*.test.*","*.spec.*"])
  -s, --subdirectories              Include subdirectories (default: false)
  -c, --config <path>               Path to config file
  --header <comment>                Custom header comment for generated files
  --no-sort                         Do not sort exports alphabetically
  -V, --verbose                     Show detailed output (default: false)
  -h, --help                        Display help for command

Commands:
  init [options]                    Create a barrel-craft.json configuration file
  clean [options]                   Clean old barrel files with matching header comments

Configuration File Options

| Option | Type | Default | Description | | ---------------- | -------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | headerComment | string | "// Auto-generated by barrel-craft\n\n" | Header comment for generated files | | targets | string[] | ["src"] | Directories to process (normal mode) - creates barrels only for directories with files | | forceGenerate | string[] | [] | Directories for forced recursive generation - creates barrels for ALL subdirectories, even empty ones with valid subdirectories | | exclude | string[] | ["**/*.test.*", "**/*.spec.*", "**/*.d.ts"] | Patterns to exclude | | extensions | string[] | ["ts", "tsx"] | File extensions to process | | sortExports | boolean | true | Whether to sort export statements | | subdirectories | boolean | true | Whether to process subdirectories in targets mode | | verbose | boolean | false | Show detailed output for each file | | force | boolean | false | Clean all index files (clean command only) |

Targets vs ForceGenerate

Understanding the difference between targets and forceGenerate is crucial for effective barrel generation:

Targets (Normal Mode)

  • Creates barrel files only for directories that contain actual source files
  • Skips empty directories
  • Respects the subdirectories setting
  • Best for standard project structures

ForceGenerate (Forced Mode)

  • Creates barrel files for ALL directories in the path, recursively
  • Includes empty directories if they contain valid subdirectories
  • Always processes subdirectories regardless of the subdirectories setting
  • Perfect for maintaining consistent structure in special directories like pages or routes

Example Scenario:

Given this structure:

src/
├── components/
│   ├── ui/
│   │   ├── Button.tsx
│   │   └── Modal.tsx
│   └── composite/
│       ├── UserCard.tsx
│       └── UserList.tsx
├── services/
│   ├── api/
│   │   ├── auth.service.ts
│   │   └── user.service.ts
│   └── storage/
│       ├── local-storage.service.ts
│       └── session-storage.service.ts
└── pages/
    ├── auth/
    │   └── login/
    │       └── LoginPage.tsx
    └── dashboard/
        └── DashboardPage.tsx

Configuration:

{
  "targets": ["src"],
  "forceGenerate": ["src/services", "src/pages"],
  "subdirectories": true
}

Result:

  • targets will create barrels for directories with files (skipping src/services and its subdirs as they're in forceGenerate)
  • forceGenerate will create:
    • src/services/index.ts (exports ./api and ./storage)
    • src/services/api/index.ts (exports services)
    • src/services/storage/index.ts (exports services)
    • src/pages/index.ts (exports ./auth and ./dashboard)
    • src/pages/auth/index.ts (exports ./login)
    • src/pages/auth/login/index.ts (exports LoginPage)
    • src/pages/dashboard/index.ts (exports DashboardPage)

Subdirectories Processing

The subdirectories option controls whether barrel-craft processes nested directories in targets mode only:

  • subdirectories: true (default): Processes all subdirectories recursively in targets
  • subdirectories: false: Only processes the target directory itself
  • Note: forceGenerate always processes subdirectories recursively

CLI vs Config File:

  • CLI flag: --subdirectories overrides config file setting
  • Config file: "subdirectories": true behaves the same as --subdirectories flag
  • Default behavior: When using init command, subdirectories is set to true by default

Example:

# These are equivalent when config has "subdirectories": true
barrel-craft ./src
barrel-craft ./src --subdirectories

Verbose Output

The verbose option controls the level of detail in the output:

  • verbose: false (default): Shows only a summary count
  • verbose: true: Shows detailed information for each generated file

Output Examples:

Default (verbose=false):

✅ Generated 10 barrel file(s)

Verbose (verbose=true):

   /path/to/src/components/index.ts (5 exports) [normal]
   /path/to/src/utils/index.ts (2 exports) [normal]
   /path/to/src/services/api/index.ts (3 exports) [forced]
   /path/to/src/services/storage/index.ts (2 exports) [forced]
   /path/to/src/services/index.ts (2 exports) [forced]

✅ Generated 10 barrel file(s)

The [normal] and [forced] indicators show which generation mode was used for each file.

CLI vs Config File:

  • CLI flag: -V, --verbose overrides config file setting
  • Config file: "verbose": true shows detailed output
  • Default behavior: verbose is set to false for cleaner output in large projects

Variable Patterns

The configuration supports variable patterns for flexible path matching:

{
  "targets": ["src/{components|utils}"],
  "forceGenerate": ["src/{auth|dashboard}/pages"]
}

This expands to:

  • targets: ["src/components", "src/utils"]
  • forceGenerate: ["src/auth/pages", "src/dashboard/pages"]

Clean Command

The clean command helps remove old barrel files that may conflict with new ones:

# Preview what would be cleaned (recommended first step)
barrel-craft clean --dry-run

# Clean files with matching header comments only (safe)
barrel-craft clean

# Force clean all index.ts/tsx files (use with caution)
barrel-craft clean --force

# Clean with specific config file
barrel-craft clean -c my-config.json

Clean Options:

  • --dry-run: Shows what files would be cleaned without actually deleting them
  • --force: Removes all index.ts/tsx files regardless of header comments
  • -c, --config <path>: Use specific configuration file

Safety Features:

  • By default: Only removes files with matching header comments to avoid deleting user-created index files
  • Header detection: Automatically detects auto-generated files from previous tools or barrel-craft runs
  • Config support: Supports "force": true in configuration file for automated cleaning

Example with config file:

{
  "headerComment": "// Auto-generated by barrel-craft\n\n",
  "targets": ["src"],
  "force": true
}
barrel-craft clean  # Will use force: true from config

📋 Examples

Basic Usage

# Process current directory
barrel-craft

# Process specific directory with custom extensions
barrel-craft ./src --extensions js jsx

# Exclude additional patterns
barrel-craft ./src --exclude "*.test.*" "*.stories.*" "*.d.ts"

Real-World Configuration

Create barrel-craft.json for a typical React/TypeScript project:

{
  "headerComment": "// 🛢️ Auto-generated barrel file\n// Do not edit manually\n\n",
  "targets": ["src"],
  "forceGenerate": ["src/services", "src/pages", "src/features/*/components"],
  "exclude": [
    "**/*.test.*",
    "**/*.spec.*",
    "**/*.stories.*",
    "**/components/ui/**"
  ],
  "extensions": ["ts", "tsx"],
  "sortExports": true,
  "subdirectories": true,
  "verbose": false
}

This configuration will:

  • Process all directories under src/ that contain files (targets)
  • Force-generate complete barrel trees for:
    • src/services/ - All service modules with nested structure
    • src/pages/ - All page components maintaining route hierarchy
    • src/features/*/components - Component folders in each feature
  • Skip test files, stories, and UI component library
  • Process both TypeScript and React files

Then run:

barrel-craft

Force Generation Mode

The forceGenerate configuration is powerful for maintaining consistent barrel structure:

{
  "targets": ["src"],
  "forceGenerate": ["src/pages", "src/layouts", "src/services"]
}

Key differences from targets:

  • Creates barrel files for every directory in the path, recursively
  • Includes directories that only contain subdirectories (no direct files)
  • Essential for re-exporting nested modules through parent barrels
  • Directories in forceGenerate are automatically excluded from targets processing to avoid duplication

Use cases:

  • Pages/Routes: Maintain navigation structure through barrel files
  • Services: Group related services with clean import paths
  • Feature modules: Organize features with proper encapsulation

🔧 Generated Output Examples

TypeScript Files Only

// Auto-generated by barrel-craft

export * from "./AuthService";
export * from "./UserService";
export * from "./ValidationService";

Mixed TypeScript and React Files

// Auto-generated by barrel-craft

export * from "./Button";
export * from "./Modal";
export * from "./UserCard";

With Subdirectories

// Auto-generated by barrel-craft

export * from "./auth";
export * from "./components";
export * from "./UserService";
export * from "./ValidationService";

🤝 Contributing

We welcome contributions! Here's how you can help:

Development Setup

  1. Clone the repository
git clone https://github.com/marcioaltoe/barrel-craft.git
cd barrel-craft
  1. Install dependencies
bun install
  1. Development commands
bun run dev          # Development mode with file watching
bun run test         # Run tests
bun run test:watch   # Run tests in watch mode
bun run test:ui      # Run tests with UI interface
bun run build        # Build for distribution
bun run lint         # Lint and auto-fix
bun run format       # Format code

Project Structure

src/
├── core/
│   └── barrel-generator.ts    # Main barrel generation logic
├── utils/
│   ├── config-loader.ts       # Configuration file handling
│   └── pattern-expander.ts    # Variable pattern expansion
├── types/
│   └── index.ts              # TypeScript interfaces
├── cli.ts                    # CLI entry point
└── index.ts                  # Library exports

tests/
├── barrel-generator.test.ts
├── config-loader.test.ts
└── pattern-expander.test.ts

Guidelines

  • Code Quality: All code must pass linting (bun run lint) and formatting (bun run format)
  • Testing: Write tests for new features and maintain 100% test coverage
  • TypeScript: Use strict TypeScript with proper typing
  • Commits: Use conventional commit messages
  • Documentation: Update README and JSDoc comments for new features

Running Tests

# Run all tests
bun run test

# Run specific test file
bun run test tests/barrel-generator.test.ts

# Run tests with coverage
bun run test --coverage

Submitting Changes

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests for your changes
  5. Ensure all tests pass (bun test)
  6. Commit your changes (git commit -m 'feat: add amazing feature')
  7. Push to the branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • Built with Commander.js for CLI functionality
  • Uses glob for file pattern matching
  • Developed with Bun for fast development experience
  • Tested with Vitest for reliable testing

🏠 Home📚 Documentation🐛 Issues💡 Discussions