blade-formatter Documentation

repository·main·Indexed 20 days ago

https://github.com/shufo/blade-formatter

An opinionated formatter for Laravel Blade templates (v1.44.4) that handles indentation, spacing, and Tailwind CSS class sorting. It provides a BladeFormatter class for programmatic formatting and a CLI workflow for processing files. Configuration can be managed via .bladeformatterrc.json or .bladeformatterrc files, allowing customization of indent size, line wrapping, attribute sorting, and PHP syntax compatibility.

Tokens
2.8K
Snippets
6
Records
9
Agent score
69%

What's inside blade-formatter

  1. Configure blade-formatter via configuration files

    main

    blade-formatter looks for configuration files in the directory of the file being formatted. It searches for the following filenames in order:

    1. .bladeformatterrc.json
    2. .bladeformatterrc

    If a configuration file is found, its contents are parsed as JSON and used to apply formatting rules.

  2. Configure BladeFormatter options

    main

    The BladeFormatterOption type combines CLI-specific flags and core formatting rules.

    Core Formatting Options

    • indentSize: Number of spaces for indentation.
    • wrapLineLength: Maximum line length before wrapping.
    • wrapAttributes: Strategy for wrapping HTML attributes (WrapAttributes).
    • wrapAttributesMinAttrs: Minimum number of attributes required to trigger wrapping.
    • indentInnerHtml: Whether to indent content inside HTML tags.
    • endWithNewline: Whether to ensure the file ends with a newline.
    • endOfLine: Line ending style (EndOfLine).
    • useTabs: Use tabs instead of spaces.
    • sortTailwindcssClasses: If true, sorts Tailwind CSS classes (requires tailwindcssConfigPath or tailwindcssConfig).
    • sortHtmlAttributes: Sorts HTML attributes (SortHtmlAttributes).
    • customHtmlAttributesOrder: Custom order for HTML attributes.
    • noMultipleEmptyLines: Removes multiple consecutive empty lines.
    • noPhpSyntaxCheck: Disables PHP syntax checking.
    • noSingleQuote: Forces double quotes.
    • noTrailingCommaPhp: Removes trailing commas in PHP.
    • phpVersion: Specifies the PHP version for syntax compatibility.

    CLI Options

    • write: If true, overwrites the original files with formatted content.
    • diff: If true, prints the differences between original and formatted content.
    • checkFormatted: If true, checks if files are already formatted and exits with code 1 if they are not.
    • progress: If true, shows progress indicators (F for fixed, . for unchanged, E for error).
    • ignoreFilePath: Path to a custom ignore file.
    • runtimeConfigPath: Path to a custom runtime configuration file.
  3. Format PHP comments with formatPhpComment()

    main

    The formatPhpComment function is used to format PHP-style comments (often found in Blade templates). If the comment is a single line, it returns the input unchanged. For multiline comments, it ensures that subsequent lines (after the first line) are properly indented/prefixed if they are part of the comment block. It specifically looks for lines starting with * to apply formatting.

    import { formatPhpComment } from 'blade-formatter';
    
    const formatted = formatPhpComment(
    `/**
     * This is a
     * multiline comment
     */`
    );
    // Returns the formatted string
  4. Use the BladeFormatter class for programmatic formatting

    main

    The BladeFormatter class is the primary entry point for integrating Blade formatting into your application. You can use it to format a single string of content or to process multiple files from the CLI-style workflow.

    Formatting a string

    Use the format(content, options) method to format a raw string. This method automatically resolves configuration files like .bladeignore, tailwind.config.js, and runtime configuration files in the current working directory.

    Processing files

    Initialize the class with a list of file paths and use formatFromCLI() to execute a full workflow that includes globbing, filtering (via .bladeignore), and writing changes to disk (if the write option is enabled).

    import { BladeFormatter } from 'blade-formatter';
    
    // 1. Format a single string
    const formatter = new BladeFormatter({ write: true });
    const formatted = await formatter.format('<div class="foo"></div>');
    
    // 2. Format multiple files (CLI-style)
    const cliFormatter = new BladeFormatter({
      write: true, 
      progress: true 
    }, ['resources/views/**/*.blade.php']);
    await cliFormatter.formatFromCLI();
  5. Find and read runtime configuration programmatically

    main

    If you are integrating blade-formatter into your own tool, you can use the following functions to discover and load configuration files:

    • findRuntimeConfig(filePath: string): Returns the path to the configuration file found in the directory of the provided filePath, or null if none is found.
    • readRuntimeConfig(filePath: string | null): Takes a file path (or null) and returns a validated RuntimeConfig object. It throws an error if the JSON is invalid according to the schema.
    import { findRuntimeConfig, readRuntimeConfig } from 'blade-formatter';
    
    async function loadConfig(targetFile: string) {
      const configPath = findRuntimeConfig(targetFile);
      const config = await readRuntimeConfig(configPath);
      return config;
    }
  6. Directives with special indentation rules

    main

    Certain Blade directives follow specific structural rules that differ from standard start/end pairs:

    • Optional Start without End Tokens: These directives (e.g., @section, @push, @prepend, @slot) may not require an explicit end token if they are provided with specific parameters.
    • Unbalanced Start Tokens: The @hassection directive is identified as an unbalanced start token.
    • Inline Function Tokens: A set of tokens used for inline logic or property assignment (e.g., @set, @js, @props, @aware).
  7. Blade directive token categories

    main

    The formatter uses specific token lists to determine indentation and structure for Blade templates. These tokens include:

    • Start Tokens: Directives that begin a block (e.g., @if, @foreach, @section).
    • End Tokens: Directives that close a block (e.g., @endif, @endforeach, @endsection).
    • Else/Elseif Tokens: Directives used for conditional branching (e.g., @else, @elseif).
    • Inline Directives: Directives typically used within an expression or on a single line (e.g., @class, @include, @json).
    • PHP Keyword Tokens: Tokens specifically related to PHP control structures within Blade (e.g., @for, @while, @break).
    • CSS At-Rule Tokens: Standard CSS at-rules that the formatter recognizes (e.g., @media, @keyframes, @import).
    // Example of token categories used by the formatter:
    // indentStartTokens: ["@if", "@foreach", "@section", ...]
    // indentEndTokens: ["@endif", "@endforeach", "@endsection", ...]
    // indentElseTokens: ["@else", "@elseif", ...]
    // inlinePhpDirectives: ["@class", "@include", ...]
    // cssAtRuleTokens: ["@media", "@keyframes", ...]
  8. Reference: RuntimeConfig options

    main

    The RuntimeConfig object defines the formatting rules for blade-formatter. Below are the available configuration keys and their allowed values.

    ```json
    {
      "indentSize": 4,
      "wrapLineLength": 80,
      "wrapAttributes": "auto",
      "wrapAttributesMinAttrs": 2,
      "indentInnerHtml": true,
      "endWithNewline": true,
      "endOfLine": "LF",
      "useTabs": false,
      "sortTailwindcssClasses": true,
      "tailwindcssConfigPath": "/path/to/tailwind.config.js",
      "sortHtmlAttributes": "alphabetical",
      "customHtmlAttributesOrder": ["id", "class"],
      "noMultipleEmptyLines": true,
      "noPhpSyntaxCheck": true,
      "noSingleQuote": true,
      "noTrailingCommaPhp": true,
      "extraLiners": ["head", "body", "/html"],
      "componentPrefix": ["x-", "livewire:"]
    }

    Attribute Wrapping (wrapAttributes)

    Options:

    • "auto"
    • "force"
    • "force-aligned"
    • "force-expand-multiline"
    • "aligned-multiple"
    • "preserve"
    • "preserve-aligned"

    HTML Attribute Sorting (sortHtmlAttributes)

    Options:

    • "none"
    • "alphabetical"
    • "code-guide"
    • "idiomatic"
    • "vuejs"
    • "custom" (requires customHtmlAttributesOrder)

    Line Endings (endOfLine)

    Options:

    • "LF"
    • "CRLF"
  9. Reference: BladeFormatterOption properties

    main

    The following properties are available in the BladeFormatterOption object used to configure the formatter behavior.

    export type FormatterOption = {
    	indentSize?: number;
    	wrapLineLength?: number;
    	wrapAttributes?: WrapAttributes;
    	wrapAttributesMinAttrs?: number;
    	indentInnerHtml?: boolean;
    	endWithNewline?: boolean;
    	endOfLine?: EndOfLine;
    	useTabs?: boolean;
    	sortTailwindcssClasses?: true;
    	tailwindcssConfigPath?: string;
    	tailwindcssConfig?: TailwindConfig;
    	sortHtmlAttributes?: SortHtmlAttributes;
    	customHtmlAttributesOrder?: string[] | string;
    	noMultipleEmptyLines?: boolean;
    	noPhpSyntaxCheck?: boolean;
    	noSingleQuote?: boolean;
    	noTrailingCommaPhp?: boolean;
    	extraLiners?: string[];
    	componentPrefix?: string[];
    	phpVersion?: string;
    };
    
    export type CLIOption = {
    	write?: boolean;
    	diff?: boolean;
    	checkFormatted?: boolean;
    	progress?: boolean;
    	ignoreFilePath?: string;
    	runtimeConfigPath?: string;
    };