dedent

repository·main·Indexed 22 days ago

https://github.com/dmnd/dedent

A string tag and function (version 1.7.2) that strips common leading indentation from multi-line strings. It can be used as a tagged template literal or a standard function to maintain code readability without including unwanted whitespace in the final output. It includes a `withOptions()` method to configure behavior such as `alignValues` for interpolated multi-line strings, `escapeSpecialCharacters` for handling special characters, and `trimWhitespace` for removing leading and trailing whitespace.

Tokens
2.3K
Snippets
11
Records
12
Agent score
77%

What's inside dedent

  1. Use dedent as a template tag or function

    main

    You can use dedent in two ways:

    1. As a template tag: Use backticks (`) to strip indentation from multi-line strings while keeping the code readable.
    2. As a function: Pass a string directly to dedent() to strip its indentation.

    By default, dedent also trims leading and trailing lines from the resulting string.

    import dedent from "dedent";
    
    // As a template tag
    const first = dedent`A string that gets so long you need to break it over
    								 multiple lines.`;
    
    // As a function
    const third = dedent(`
    	Wait! I lied. Dedent can also be used as a function.
    `);
  2. Configure the alignValues option

    main

    When an interpolated value (e.g., ${list}) is a multi-line string, subsequent lines often lose their relative indentation, causing them to appear "shifted left" compared to the first line.

    Setting alignValues: true ensures that every line after the first in an interpolated multi-line string receives extra indentation so that it aligns with the column of the first line.

    import dedent from "dedent";
    
    const list = dedent`
    	- apples
    	- bananas
    	- cherries
    `;
    
    // Without alignValues (default), lines may shift left
    const withoutAlign = dedent`
    	List without alignValues (default):
    		${list}
    	Done.
    `;
    
    // With alignValues: true, lines stay aligned with the first line of the interpolation
    const withAlign = dedent.withOptions({ alignValues: true })`
    	List with alignValues: true
    		${list}
    	Done.
    `;
  3. Configure the escapeSpecialCharacters option

    main

    By default, when used as a template tag, dedent escapes special characters (like $) by adding a backslash (\). When used as a function, it does not escape them.

    You can override this behavior using escapeSpecialCharacters:

    • true: Always escape special characters (default for template tags).
    • false: Never escape special characters (default for functions).
    import dedent from "dedent";
    
    // Default tag behavior: "$hello!"
    dedent`\n\t$hello!\n`;
    
    // Disable escaping: "$hello!"
    dedent.withOptions({ escapeSpecialCharacters: false })`\n\t$hello!\n`;
    
    // Force escaping: "\$hello!"
    dedent.withOptions({ escapeSpecialCharacters: true })`\n\t$hello!\n`;
  4. Align multi-line interpolated values with alignValues

    main

    By default, interpolated values in a template literal are inserted as-is. If you set alignValues: true in your DedentOptions, dedent will detect the indentation of the current line and apply that same indentation to every new line within a multi-line interpolated value. This ensures that injected content maintains the visual structure of the template.

    import dedent from 'dedent';
    
    const customDedent = dedent.withOptions({ alignValues: true });
    
    const multiLine = "    line1\n    line2";
    const result = customDedent`
        Start
        ${multiLine}
        End
    `;
    // The lines in 'multiLine' will be aligned to the indentation of the line containing '${multiLine}'
  5. Configure the trimWhitespace option

    main

    By default, dedent trims leading and trailing whitespace from the overall resulting string. You can disable this by setting trimWhitespace: false in the options object.

    import dedent from "dedent";
    
    // Default: trims whitespace
    dedent`\n\thello! \n`;
    
    // Disabled: preserves leading/trailing whitespace
    dedent.withOptions({ trimWhitespace: false })`\n\thello! \n`;
    
    // Explicitly enabled
    dedent.withOptions({ trimWhitespace: true })`\n\thello! \n`;
  6. Configure dedent with withOptions()

    main

    To customize how dedent behaves, use the withOptions() method. This method returns a new function that applies the specified configuration. You can use this new function as a template tag or as a standard function.

    If you want to reuse the same configuration multiple times, create a dedicated instance using withOptions().

    import dedent from 'dedent';
    
    // Create a reusable dedenter with specific options
    const dedenter = dedent.withOptions({ /* ... */ });
    
    dedenter`input`;
    dedenter(`input`);
  7. Configure DedentOptions

    main

    When using withOptions or initializing dedent, you can provide the following configuration keys:

    • alignValues: (boolean, default: false) If true, multi-line interpolated values will have their indentation automatically adjusted to match the indentation of the line they are being inserted into.
    • escapeSpecialCharacters: (boolean, default: true when used as a template tag) If true, handles escaping of backticks, interpolation characters ($, {), and converts escaped sequences like \n or \u{...} into their actual character equivalents.
    • trimWhitespace: (boolean, default: true) If true, leading and trailing whitespace of the entire resulting string is removed.
  8. Configure Dedent options

    main

    When creating a custom dedent function using withOptions, you can provide a DedentOptions object to control how whitespace and special characters are handled.

    Available options:

    • alignValues (boolean, optional): Controls whether values interpolated into the template string are aligned.
    • escapeSpecialCharacters (boolean, optional): Controls whether special characters are escaped.
    • trimWhitespace (boolean, optional): Controls whether leading/trailing whitespace is trimmed.
    interface DedentOptions {
    	alignValues?: boolean;
    	escapeSpecialCharacters?: boolean;
    	trimWhitespace?: boolean;
    }
  9. Configure dedent options with withOptions()

    main

    You can create a new instance of the dedent function with custom configuration by using the .withOptions(options) method. This returns a new dedent function that applies the provided DedentOptions to every call.

    import dedent from 'dedent';
    
    const customDedent = dedent.withOptions({
      trimWhitespace: false,
      alignValues: true
    });
    
    const result = customDedent`
        Indented text
    `;
  10. Use the Dedent interface

    main

    The Dedent interface defines the shape of the dedent function. It can be used in two ways:

    1. As a tagged template literal: Pass TemplateStringsArray and interpolated values directly.
    2. As a standard function: Pass a single string literal.

    It also provides a withOptions method to create a new dedent function pre-configured with specific DedentOptions.

    // As a tagged template literal
    const result = dedent`  hello ${'world'}`;
    
    // As a standard function
    const result = dedent('  hello');
    
    // Creating a configured version
    const customDedent = dedent.withOptions({ trimWhitespace: true });
    const result = customDedent`  hello`;
  11. Use the dedent tag function

    main

    The dedent function is a tagged template literal that removes common leading indentation from multi-line strings. It can be used as a template tag or as a regular function call. It automatically calculates the minimum indentation of all non-empty lines and strips that amount from every line.

    import dedent from 'dedent';
    
    const message = dedent`
        Hello
        World
    `;
    // "Hello\nWorld"