npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@plasmohq/prettier-plugin-sort-imports

v4.0.1

Published

A prettier plugins to sort imports in provided RegEx order

Downloads

5,562

Readme

Prettier plugin sort imports

A prettier plugin to sort import declarations by provided Regular Expression order.

This was forked from IanVS/prettier-plugin-sort-imports, which was a fork of @trivago/prettier-plugin-sort-imports.

Sample

Input

// prettier-ignore
import { environment } from "./misguided-module-with-side-effects.js";

import "core-js/stable"
import "regenerator-runtime/runtime"

import { initializeApp } from "@core/app"
import { logger } from "@core/logger"
import { createConnection } from "@server/database"
import { createServer } from "@server/node"
import { Alert } from "@ui/Alert"
import { Popup } from "@ui/Popup"
import { debounce, reduce } from "lodash"
import React, { ChangeEvent, FC, KeyboardEvent, useEffect, useRef } from "react"

import { Message } from "../Message"
import { add, filter, repeat } from "../utils"

Output

// prettier-ignore
import { environment } from "./misguided-module-with-side-effects.js";

import "core-js/stable"
import "regenerator-runtime/runtime"

import { initializeApp } from "@core/app"
import { logger } from "@core/logger"
import { createConnection } from "@server/database"
import { createServer } from "@server/node"
import { Alert } from "@ui/Alert"
import { Popup } from "@ui/Popup"
import { debounce, reduce } from "lodash"
import React, { ChangeEvent, FC, KeyboardEvent, useEffect, useRef } from "react"

import { Message } from "../Message"
import { add, filter, repeat } from "../utils"

Install

pnpm install --save-dev @plasmohq/prettier-plugin-sort-imports

Usage

Add your preferred settings in your prettier config file.

/**
 * @type {import('prettier').Options}
 */
module.exports = {
  printWidth: 80,
  tabWidth: 2,
  useTabs: false,
  semi: false,
  singleQuote: false,
  trailingComma: "none",
  bracketSpacing: true,
  bracketSameLine: true,
  plugins: [require("./dist/index.js")],
  importOrder: ["^@plasmo/(.*)$", "^@plasmohq/(.*)$", "^~(.*)$", "^[./]"],
  importOrderSeparation: true,
  importOrderSortSpecifiers: true,
  importOrderBuiltinModulesToTop: true,
  importOrderCaseInsensitive: true,
  importOrderParserPlugins: ["typescript", "jsx", "decorators-legacy"],
  importOrderMergeDuplicateImports: true
}

Note: all flags are off by default, so explore your options below

APIs

Prevent imports from being sorted

This plugin supports standard prettier ignore comments. By default, side-effect imports (like import "core-js/stable";) are not sorted, so in most cases things should just work. But if you ever need to, you can prevent an import from getting sorted like this:

// prettier-ignore

import { cars } from "austria";
import { goods } from "zealand"

This will keep the zealand import at the top instead of moving it below the austria import. Note that since only entire import statements can be ignored, line comments (// prettier-ignore) are recommended over inline comments (/* prettier-ignore */).

importOrder

type: Array<string>

A collection of Regular expressions in string format.

"importOrder": ["^@core/(.*)$", "^@server/(.*)$", "^@ui/(.*)$", "^[./]"],

Default: []

By default, this plugin will not move any imports. To separate third party from relative imports, use ["^[./]"]. This will become the default in the next major version.

The plugin moves the third party imports to the top which are not part of the importOrder list. To move the third party imports at desired place, you can use <THIRD_PARTY_MODULES> to assign third party imports to the appropriate position:

"importOrder": ["^@core/(.*)$", "<THIRD_PARTY_MODULES>", "^@server/(.*)$", "^@ui/(.*)$", "^[./]"],

importOrderSeparation

type: boolean

default value: false

A boolean value to enable or disable the new line separation between sorted import declarations group. The separation takes place according to the importOrder.

"importOrderSeparation": true,

Note: If you want greater control over which groups are separated from others, you can add an empty string to your importOrder array to signify newlines. For example:

"importOrderSeparation": false,
"importOrder": [
   "^react", // React will be placed at the top of third-party modules
    "<THIRD_PARTY_MODULES>",
    "",  // use empty strings to separate groups with empty lines
    "^[./]"
],

importOrderSortSpecifiers

type: boolean

default value: false

A boolean value to enable or disable sorting of the specifiers in an import declarations.

importOrderGroupNamespaceSpecifiers

type: boolean

default value: false

A boolean value to enable or disable sorting the namespace specifiers to the top of the import group.

importOrderCaseInsensitive

type: boolean

default value: false

A boolean value to enable case-insensitivity in the sorting algorithm used to order imports within each match group.

For example, when false (or not specified):

import ExampleView from "./ExampleView"
import ExamplesList from "./ExamplesList"

compared with "importOrderCaseInsensitive": true:

import ExampleView from "./ExampleView"
import ExamplesList from "./ExamplesList"

importOrderMergeDuplicateImports

type: boolean

default value: false

When true, multiple import statements from the same module will be combined into a single import.

importOrderParserPlugins

type: Array<string>

default value: ["typescript", "jsx"]

Previously known as experimentalBabelParserPluginsList.

A collection of plugins for babel parser. The plugin passes this list to babel parser, so it can understand the syntaxes used in the file being formatted. The plugin uses prettier itself to figure out the parser it needs to use but if that fails, you can use this field to enforce the usage of the plugins' babel parser needs.

To pass the plugins to babel parser:

  "importOrderParserPlugins" : ["classProperties", "decorators-legacy"]

To pass the options to the babel parser plugins: Since prettier options are limited to string, you can pass plugins with options as a JSON string of the plugin array: "[\"plugin-name\", { \"pluginOption\": true }]".

  "importOrderParserPlugins" : ["classProperties", "[\"decorators\", { \"decoratorsBeforeExport\": true }]"]

To disable default plugins for babel parser, pass an empty array:

"importOrderParserPlugins": []

importOrderBuiltinModulesToTop

type: boolean

default value: false

A boolean value to enable sorting of node builtins to the top of all import groups.

How does import sort work?

The plugin extracts the imports which are defined in importOrder. These imports are considered as local imports. The imports which are not part of the importOrder is considered as third party imports.

First, the plugin checks for side effect imports, such as import 'mock-fs'. These imports often modify the global scope or apply some patches to the current environment, which may affect other imports. To preserve potential side effects, these kind of side effect imports are classified as unsortable. They also behave as a barrier that other imports may not cross during the sort. So for example, let's say you've got these imports:

import D from "d"
import E from "e"
import F from "f"

import "c"

import A from "a"
import B from "b"

Then the first three imports are sorted and the last two imports are sorted, but all imports above c stay above c and all imports below c stay below c, resulting in:

import D from "d"
import E from "e"
import F from "f"

import "c"

import A from "a"
import B from "b"

Additionally, any import statements lines that are preceded by a // prettier-ignore comment are also classified as unsortable. This can be used for edge-cases, such as when you have a named import with side-effects.

Next, the plugin sorts the local imports and third party imports using natural sort algorithm.

In the end, the plugin returns final imports with third party imports on top and local imports at the end.

The third party imports position (it's top by default) can be overridden using the <THIRD_PARTY_MODULES> special word in the importOrder.

FAQ / Troubleshooting

Having some trouble or an issue? You can check FAQ / Troubleshooting section.

Compatibility

| Framework | Supported | Note | | ---------------------- | ------------------------ | ------------------------------------------------ | | JS with ES Modules | ✅ Everything | - | | NodeJS with ES Modules | ✅ Everything | - | | React | ✅ Everything | - | | Angular | ✅ Everything | Supported through importOrderParserPlugins API | | Vue | ⚠️ Soon to be supported. | Any contribution is welcome. | | Svelte | ⚠️ Soon to be supported. | Any contribution is welcome. |

Contribution

For more information regarding contribution, please check the Contributing Guidelines. If you are trying to debug some code in the plugin, check Debugging Guidelines

Disclaimer

This plugin modifies the AST which is against the rules of prettier.