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
Maintainers
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
.tsxwhen 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.tsxwhen generatingindex.ts
📦 Installation
Global Installation (Recommended)
npm install -g barrel-craftLocal 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 --verboseConfiguration File
Create a configuration file for advanced usage:
barrel-craft initThis 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 commentsConfiguration 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
subdirectoriessetting - 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
subdirectoriessetting - 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.tsxConfiguration:
{
"targets": ["src"],
"forceGenerate": ["src/services", "src/pages"],
"subdirectories": true
}Result:
targetswill create barrels for directories with files (skippingsrc/servicesand its subdirs as they're inforceGenerate)forceGeneratewill create:src/services/index.ts(exports./apiand./storage)src/services/api/index.ts(exports services)src/services/storage/index.ts(exports services)src/pages/index.ts(exports./authand./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 targetssubdirectories: false: Only processes the target directory itself- Note:
forceGeneratealways processes subdirectories recursively
CLI vs Config File:
- CLI flag:
--subdirectoriesoverrides config file setting - Config file:
"subdirectories": truebehaves the same as--subdirectoriesflag - Default behavior: When using
initcommand,subdirectoriesis set totrueby default
Example:
# These are equivalent when config has "subdirectories": true
barrel-craft ./src
barrel-craft ./src --subdirectoriesVerbose Output
The verbose option controls the level of detail in the output:
verbose: false(default): Shows only a summary countverbose: 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, --verboseoverrides config file setting - Config file:
"verbose": trueshows detailed output - Default behavior:
verboseis set tofalsefor 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.jsonClean 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": truein 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 structuresrc/pages/- All page components maintaining route hierarchysrc/features/*/components- Component folders in each feature
- Skip test files, stories, and UI component library
- Process both TypeScript and React files
Then run:
barrel-craftForce 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
forceGenerateare automatically excluded fromtargetsprocessing 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
- Clone the repository
git clone https://github.com/marcioaltoe/barrel-craft.git
cd barrel-craft- Install dependencies
bun install- 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 codeProject 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.tsGuidelines
- 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 --coverageSubmitting Changes
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Add tests for your changes
- Ensure all tests pass (
bun test) - Commit your changes (
git commit -m 'feat: add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - 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
