@ianvs/prettier-plugin-sort-imports

repository·main·Indexed 23 days ago

https://github.com/ianvs/prettier-plugin-sort-imports

A Prettier plugin that sorts import declarations using Regular Expressions. It features side-effect preservation, import combining, specialized grouping for types and built-in modules, and support for various frameworks including React, Svelte, Angular, and Vue.

Tokens
5.2K
Snippets
13
Records
32
Agent score
72%

What's inside @ianvs/prettier-plugin-sort-imports

  1. Overview of @ianvs/prettier-plugin-sort-imports

    main

    This Prettier plugin sorts import declarations based on a provided Regular Expression order. It improves upon @trivago/prettier-plugin-sort-imports with several additional features:

    • Side-effect preservation: Does not re-order across side-effect imports by default.
    • Import combining: Combines imports from the same source and merges type and value imports (when importOrderTypeScriptVersion is set to "4.5.0" or higher).
    • Type grouping: Groups type imports using the <TYPES> keyword.
    • Built-in module support: Sorts Node.js built-in modules to the top (configurable via the <BUILTIN_MODULES> keyword).
    • Customization: Supports custom import order separation, handles comments around imports correctly, and simplifies configuration options.
  2. How import sorting works

    main

    The plugin categorizes imports into two main groups:

    1. Local imports: Imports that match the regular expressions defined in importOrder.
    2. Third party imports: Imports that do not match any regex in importOrder.

    Sorting Logic and Barriers

    • Side-effect imports: Imports like import 'mock-fs' are classified as unsortable. They act as a barrier: imports above a side-effect import stay above it, and imports below stay below it. They are not moved during sorting.
    • Prettier ignore: Any import statement preceded by a // prettier-ignore comment is treated as unsortable.
    • Algorithm: Local and third-party imports are sorted using a natural sort algorithm.
    • Default Order: By default, the plugin orders imports as: Node.js built-in modules $\rightarrow$ Third party imports $\rightarrow$ Local imports.
  3. Control import group separation using empty strings in v4.x.x

    main

    In v4.x.x, the importOrderSeparation option has been removed. To create gaps (blank lines) between import groups, insert empty strings "" into your importOrder array.

    Example: adding a gap at the top and between specific groups:

    "importOrder": [
        "", // Gap at the top after top-of-file-comments
        "<BUILTIN_MODULES>",
        "",
        "<THIRD_PARTY_MODULES>",
        "",
        "^@app/(.*)$",
        "",
        "^[./]"
    ]

    Example: adding a newline only before side-effect imports:

    "importOrder": [
        "<THIRD_PARTY_MODULES>",
        "^@app/(.*)$",
        "^[./]",
        "", // Adds a newline before the next group
    ]
    "importOrder": [
        "", // If you want a gap at the top after top-of-file-comments, put a separator here!
        "<BUILTIN_MODULES>",
        "",
        "<THIRD_PARTY_MODULES>",
        "",
        "^@app/(.*)$",
        "",
        "^[./]"
    ]"
  4. Install @ianvs/prettier-plugin-sort-imports

    main

    Install the plugin as a development dependency using your preferred package manager.

    Note: If you are migrating from v3.x.x to v4.x.x, refer to the migration guidelines in the repository's docs/MIGRATION.md file.

    npm install --save-dev @ianvs/prettier-plugin-sort-imports
    
    # or
    
    yarn add --dev @ianvs/prettier-plugin-sort-imports
    
    # or
    
    pnpm add --save-dev @ianvs/prettier-plugin-sort-imports
  5. Migrate from v2.x.x to v3.x.x

    main

    When upgrading from v2.x.x to v3.x.x, note the following changes:

    Breaking Changes

    • Renamed Parser Options: Replace experimentalBabelParserPluginsList with importOrderParserPlugins in your Prettier configuration.

    Key Features in v3.x.x

    • Sort Import Specifiers: Use importOrderSortSpecifiers: true to sort the names inside the curly braces of an import statement.
    • Custom Third-Party Placement: Use the <THIRD_PARTY_MODULES> keyword in your importOrder array to place third-party imports anywhere in the sequence.
    • Case Insensitivity: Use importOrderCaseInsensitive: true to disable case-sensitive sorting.
    • Group Separation: Use importOrderSeparation: true to separate import groups with newlines.
  6. Debug the plugin using Node debugger

    main

    To debug the plugin, you can insert a debugger statement in the source code and then run Prettier with the --inspect-brk flag. This command compiles the project and runs the local plugin build against the example file:

    yarn run compile && node --inspect-brk ./node_modules/.bin/prettier --config examples/.prettierrc --plugin lib/src/index.js examples/example.ts
  7. Prevent imports from being sorted

    main

    To prevent specific import statements from being moved, use the // prettier-ignore comment directly above the import. Line comments (// prettier-ignore) are preferred over inline comments (/* prettier-ignore */).

    // prettier-ignore
    import { goods } from "zealand";
    import { cars } from "austria";

    In this example, zealand will remain at the top regardless of alphabetical order.

  8. Configure @ianvs/prettier-plugin-sort-imports in Prettier

    main

    To use the plugin, add it to the plugins array in your Prettier configuration file. Since Prettier 3.0, manually specifying plugins is required. You can also configure the import order and parser settings within the same config object.

    // @ts-check
    
    /** @type {import("prettier").Config} */
    module.exports = {
        // Standard prettier options
        singleQuote: true,
        semi: true,
        // Since prettier 3.0, manually specifying plugins is required
        plugins: ['@ianvs/prettier-plugin-sort-imports'],
        // This plugin's options
        importOrder: ['^@core/(.*)$', '', '^@server/(.*)$', '', '^@ui/(.*)$', '', '^[./]'],
        importOrderParserPlugins: ['typescript', 'jsx', 'decorators-legacy'],
        importOrderTypeScriptVersion: '5.0.0',
        importOrderCaseSensitive: false,
    };