barrelsby

repository·master·Indexed 20 days ago

https://github.com/bencoveney/barrelsby

A tool for automatically generating TypeScript 'barrel' files (index.ts) to simplify module imports across a codebase. It supports multiple location modes (top, below, all, replace, branch) and export structures (flat, filesystem). Barrelsby can be used via a CLI, a JSON configuration file, or programmatically through its build function.

Tokens
5.1K
Snippets
16
Records
21
Agent score
69%

What's inside barrelsby

  1. Compare Barrelsby structure modes: flat vs filesystem

    master

    The --structure (or -s) option determines how exports are organized within the generated barrel file.

    flat mode (Default)

    Exports all modules without any nesting. This is useful for a simple list of exports.

    export * from "./barrel";
    export * from "./index";
    export * from "./directory2/script";

    filesystem mode

    Exports modules as a nested object structure that mirrors your file system directories.

    import * as directory2directory4deeplyNestedts from "./directory2/directory4/deeplyNested";
    import * as directory2scriptts from "./directory2/script";
    import * as indexts from "./index";
    export {barrelts as barrel};
    export const directory2 = {
      directory4: {
        deeplyNested: directory2directory4deeplyNestedts,
      },
      script: directory2scriptts,
    };
    export {indexts as index};
    // flat mode example
    export * from "./barrel";
    export * from "./index";
    export * from "./directory2/script";
  2. How barrels and barrelsby work

    master

    A barrel is a file (typically index.ts) that rolls up exports from several modules into a single convenient module. This simplifies import statements by allowing you to import multiple items from a single directory rather than multiple individual files.

    Example Barrel File:

    export * from "./DropDown";
    export * from "./TextBox";
    export * from "./CheckBox";

    Before (Messy Imports):

    import {DropDown} from "./src/controls/DropDown";
    import {TextBox} from "./src/controls/TextBox";
    import {CheckBox} from "./src/controls/CheckBox";

    After (Tidier Imports):

    import {DropDown, TextBox, CheckBox} from "./src/controls";
    export * from "./DropDown";
    export * from "./TextBox";
    export * from "./CheckBox";
    export * from "./DateTimePicker";
    export * from "./Slider";
  3. Quickstart: Generate barrels via npm script

    master

    To use Barrelsby in your workflow, add a script to your package.json. Using the --delete flag is recommended to ensure old barrels are removed before new ones are generated.

    1. Add the script to package.json:
    {
      "scripts": {
        "generate-barrels": "barrelsby --delete"
      }
    }
    1. Run the command:
    npm run generate-barrels
  4. How barrel file locations are determined via LocationOption

    master

    The getDestinations function determines which directories will receive barrel files based on the locationOption provided. The behavior changes depending on the following modes:

    • top (default): Only the root directory receives a barrel file.
    • below: Only the immediate subdirectories of the root directory receive barrel files.
    • all: Every directory in the entire file tree receives a barrel file.
    • replace: Barrel files are only created in directories that already contain a file with the specified barrelName. This is useful for replacing existing barrels.
    • branch: Barrel files are created in any directory that contains at least one subdirectory.

    Note: Destinations are processed from the deepest directory upwards (sorted by path length descending) to ensure nested barrels are created before their parent barrels.

    // The logic is driven by the LocationOption type:
    // 'top' | 'below' | 'all' | 'replace' | 'branch'
  5. Configure Barrelsby via CLI or JSON

    master

    Barrelsby can be configured using command-line arguments or a .json configuration file. If using a configuration file, specify its path with the -c or --config flag.

    Example Configuration File (barrelsby.json):

    {
      "directory": "./src",
      "delete": true,
      "structure": "flat"
    }
  6. Reference: Barrelsby CLI Options

    master

    The following options are available for the Barrelsby CLI to refine how barrels are created.

    -c [path] | --config [path]      Specifies the location of the barrelsby configuration file (.json).
    -d [path...] | --directory [path...] Specifies root directories to create barrels from (defaults to current directory).
    -D | --delete                    Deletes any existing barrels encountered (disabled by default).
    -e [regex...] | --exclude [regex...] Excludes files matching the specified regular expressions.
    -E | --exportDefault             Also export the default export (works only in 'flat' mode).
    -F | --fullPathname              Use full pathname for exportDefault (works only in 'flat' mode and with --exportDefault).
    -h | --help                      Displays help information.
    -i [regex...] | --include [regex...] Only include files matching the specified regular expressions.
    -l [mode] | --location [mode]    Determines where barrels are created. Modes: 
                                     - top: target directory only
                                     - below: every directory just below target
                                     - all: every directory below (and including) target
                                     - replace: only where a barrel already existed
                                     - branch: every directory containing other directories
    -L | --local                     Prevents barrels from including modules in the same directory (searches child directories instead).
    -n [name] | --name [name]        Specifies the barrel name (defaults to index.ts; .ts is appended if omitted).
    -s [mode] | --structure [mode]   The structure inside the barrel. Modes: 
                                     - flat: No nesting
                                     - filesystem: Nested structure matching the file system
    -q | --singleQuotes              Use 'single quotes' instead of "double quotes".
    -S | --noSemicolon               Omit semicolons at the end of lines.
    -H | --noHeader                  Omit the header comment at the top.
    -v | --version                   Display version number.
    -V | --verbose                   Display additional debug information.
  7. Use the Barrelsby function programmatically

    master

    You can call the Barrelsby function directly from your own code to automate the creation of index/barrel files. The function accepts an Arguments object to configure the build process, including directory targets, barrel naming, and formatting options.

    Note: The function performs asynchronous operations internally (such as building the tree and writing files) within a forEach loop. Ensure your environment supports top-level await or handle the execution flow accordingly.

    import { Barrelsby } from 'barrelsby';
    
    Barrelsby({
      directory: ['./src/components'],
      name: 'index',
      verbose: true,
      exportDefault: true,
      // ... other Arguments options
    });
  8. Configure logger verbosity via getLogger()

    master

    The getLogger function provides access to the internal logger instance. You can control the logging level by passing an options object with the isVerbose property.

    • If isVerbose is true, the logLevel is set to 'info'.
    • If isVerbose is false (default), the logLevel is set to 'error'.

    The logger is an instance of Signale and outputs to process.stdout.

    import { getLogger } from './path-to-logger';
    
    // For error-only logging (default)
    const errorLogger = getLogger();
    
    // For verbose/info logging
    const verboseLogger = getLogger({ isVerbose: true });
  9. Strip file extensions with getBasename

    master

    The getBasename function takes a relative path and removes common TypeScript extensions: .ts, .tsx, and .d.ts. It returns the shortest resulting string, effectively stripping the extension if present.

    import { getBasename } from 'barrelsby';
    
    const name = getBasename('utils/math.ts'); // returns 'utils/math'
  10. Calculate import paths with buildImportPath

    master

    The buildImportPath function calculates the string used for import statements. It determines the relative path from a starting location (either the provided baseUrl or the directory's own path) to a target file location.

    Key behaviors:

    • If baseUrl is provided, imports are calculated relative to that base.
    • It strips file extensions such as .ts, .tsx, or .d.ts using getBasename.
    • It ensures the path uses POSIX-style separators (forward slashes) via convertPathSeparator.
    • It ensures the path is relative by prefixing with ./ if the directory is not the current directory.
    import { buildImportPath } from 'barrelsby';
    
    // Returns a relative import path string
    const importPath = buildImportPath(directory, targetLocation, baseUrl);
  11. Use the build function to generate barrels

    master

    The build function is the primary entry point for programmatically generating barrel files. It iterates through a list of destinations (directories) and executes the barrel creation logic for each.

    It accepts a configuration object with the following properties:

    • addHeader: boolean
    • destinations: An array of Directory objects representing where barrels should be created.
    • quoteCharacter: The character used for quotes.
    • semicolonCharacter: The character used for semicolons.
    • barrelName: The name of the barrel file to be created.
    • logger: A logger instance for reporting progress or errors.
    • baseUrl: The base URL used for calculating relative import paths.
    • exportDefault: boolean
    • fullPathname: boolean
    • structure: StructureOption (e.g., FLAT) or undefined.
    • local: boolean
    • include: An array of strings for inclusion patterns.
    • exclude: An array of strings for exclusion patterns.
    import { build } from 'barrelsby';
    
    // Example usage of the build function
    build({
      addHeader: false,
      destinations: [{ path: './src/components' }],
      quoteCharacter: "'",
      semicolonCharacter: ';',
      barrelName: 'index',
      logger: myLogger,
      baseUrl: './src',
      exportDefault: false,
      fullPathname: false,
      structure: undefined,
      local: true,
      include: [],
      exclude: []
    });