• Stars
    star
    3,284
  • Rank 13,672 (Top 0.3 %)
  • Language
    TypeScript
  • License
    Apache License 2.0
  • Created over 4 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A prettier plugin to sort imports in typescript and javascript files by the provided RegEx order.

Prettier plugin sort imports

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

Note: If you are migrating from v2.x.x to v3.x.x, Please Read Migration Guidelines

Input

import React, {
    FC,
    useEffect,
    useRef,
    ChangeEvent,
    KeyboardEvent,
} from 'react';
import { logger } from '@core/logger';
import { reduce, debounce } from 'lodash';
import { Message } from '../Message';
import { createServer } from '@server/node';
import { Alert } from '@ui/Alert';
import { repeat, filter, add } from '../utils';
import { initializeApp } from '@core/app';
import { Popup } from '@ui/Popup';
import { createConnection } from '@server/database';

Output

import { debounce, reduce } from 'lodash';
import React, {
    ChangeEvent,
    FC,
    KeyboardEvent,
    useEffect,
    useRef,
} from 'react';

import { createConnection } from '@server/database';
import { createServer } from '@server/node';

import { initializeApp } from '@core/app';
import { logger } from '@core/logger';

import { Alert } from '@ui/Alert';
import { Popup } from '@ui/Popup';

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

Install

npm

npm install --save-dev @trivago/prettier-plugin-sort-imports

or, using yarn

yarn add --dev @trivago/prettier-plugin-sort-imports

Note: If you are migrating from v2.x.x to v3.x.x, Please Read Migration Guidelines

Note: If formatting .vue sfc files please install @vue/compiler-sfc if not in your dependency tree - this normally is within Vue projects.

Usage

Add an order in prettier config file.

module.exports = {
  "printWidth": 80,
  "tabWidth": 4,
  "trailingComma": "all",
  "singleQuote": true,
  "semi": true,
  "importOrder": ["^@core/(.*)$", "^@server/(.*)$", "^@ui/(.*)$", "^[./]"],
  "importOrderSeparation": true,
  "importOrderSortSpecifiers": true
}

**Note: There may be an issue with some package managers, such as pnpm. You can solve it by providing additional configuration option in prettier config file.

module.exports = {
    ...
    "plugins": ["@trivago/prettier-plugin-sort-imports"]
}

APIs

importOrder

type: Array<string>

A collection of Regular expressions in string format.

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

Default behavior: 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,

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 ExamplesList from './ExamplesList';
import ExampleView from './ExampleView';

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: []

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.

After, 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 βœ… Everything @vue/compiler-sfc is required
Svelte ⚠️ Soon to be supported. Any contribution is welcome.

Used by

Want to highlight your project or company ? Adding your project / company name will help plugin to gain attraction and contribution. Feel free to make a Pull Request to add your project / company name.

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

Maintainers

Ayush Sharma Behrang Yarahmadi
ayusharma @byara
@ayusharma_ @behrang_y

Disclaimer

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

More Repositories

1

parallel-webpack

Builds multi-config webpack projects in parallel
JavaScript
1,483
star
2

gollum

An n:m message multiplexer written in Go
Go
939
star
3

Heimdallr.swift

Easy to use OAuth 2 library for iOS, written in Swift.
Swift
639
star
4

cluecumber

Clear and concise reporting for the Cucumber BDD JSON format.
Java
270
star
5

Heimdall.droid

Easy to use OAuth 2 library for Android by trivago.
Kotlin
258
star
6

melody

Melody is a library for building JavaScript web applications.
JavaScript
215
star
7

Dobby

Swift helpers for mocking and stubbing
Swift
165
star
8

prettier-plugin-twig-melody

Code formatting plugin for Prettier which can handle Twig/Melody templates
JavaScript
155
star
9

cucable-plugin

Maven plugin that simplifies running Cucumber scenarios in parallel.
Java
115
star
10

triava

The triava project contains several of trivago's core libraries for Java-based projects: caching, collections, annotations, concurrency libraries and more.
Java
75
star
11

scalad

Horizontal Job Autoscaler for Nomad
Go
69
star
12

hamara

Export datasource from the existing Grafana DB into a YAML provisioning file
Go
57
star
13

tgo

trivago go utilities
Go
57
star
14

jade

A simple but yet powerful library to expose your entities through JSON API.
PHP
55
star
15

nomad-pot-driver

Nomad task driver for launching freebsd jails.
Go
54
star
16

Protector

A circuit breaker for InfluxDB
Python
48
star
17

fastutil-concurrent-wrapper

Set of concurrent wrappers around fastutil primitive maps
Java
37
star
18

babel-plugin-cloudinary

Compile cloudinary URLs at build time.
JavaScript
24
star
19

pbf-loader

Webpack loader for .proto files to be used within mapbox/pbf
JavaScript
21
star
20

rumi

trivago continuous integration executor
PHP
20
star
21

influxdbviewer

JavaScript
18
star
22

preact-hooks-testing-library

preact port of https://github.com/testing-library/react-hooks-testing-library
TypeScript
18
star
23

project-ironman

CSS skeleton / structure we used at trivago for our large scale refactoring project called Project Ironman
CSS
17
star
24

logstash-codec-protobuf

Protobuf codec for parsing data into logstash
17
star
25

samsa

A high level NodeJS stream processing library
TypeScript
17
star
26

jcha

Java Class Histogram Analyser
Java
17
star
27

hive-lambda-sting

A small library of hive UDFS using Macros to process and manipulate complex types
Java
15
star
28

reportoire

Kotlin
15
star
29

ReactiveHeimdall

Reactive wrapper around Heimdall.swift
Swift
14
star
30

chapi

chronos & marathon console client - Manage your jobs like a git repository
PHP
14
star
31

rebase

A small python library to make your data layer more robust.
Python
13
star
32

Mail-Pigeon

Mail Pigeon is a mail delivery plattform, which was created in the trivago developer days (something like the Google 20% rule) to replace some of the PHP based mailing scripts that were present that days. trivago has a lot of customers and therefore the focus laid on the fast and relyable sending process of a future mail tool. We decided to build a plattform that just can send mails in a performant manner, later on we built mail pigeon on top of it.
Java
13
star
33

boerewors

Release framework based on Python
Python
11
star
34

rtl-scss-kit

A right-to-left mixin set to create right-to-left and left-to-right css out of one scss-source
CSS
8
star
35

svn-daemon

A daemon to control a svn checkout via a web interface, written in go.
Go
8
star
36

exporter-edgecast

A Prometheus exporter for the Edgecast CDN
Go
7
star
37

triversity

trivago's university collaboration tool
Vue
7
star
38

libvips-mozjpeg-amazonlinux-buildscript

Modified libvips build script which helps to build libvips with mozjpeg support on AWS 'AmazonLinux' EC2 instances.
Shell
7
star
39

junior-java-software-engineer-casestudy

Case study for Junior Software Engineer - Java Backend Services
6
star
40

exporter-chinacache

A Prometheus exporter for the Chinacache CDN
Go
5
star
41

express-booking-selfconnect-api

trivago Express Booking - Self Connect API
PHP
5
star
42

recsys-challenge-2019-benchmarks

Run benchmark algorithms on the data sets of the RecSys Challenge 2019. https://recsys.trivago.cloud/
Python
4
star
43

create-melody-app

Create Melody apps quickly from the command line.
JavaScript
3
star
44

oauth-sdk-js

A tiny javascript library that allows to log in/register with trivago
JavaScript
2
star
45

melody-web

Public web site of the Melody JavaScript framework
HTML
2
star
46

.github

@trivago organization
2
star
47

intellij-idea-plugin

Internal IntelliJ plugin by trivago. Quick and dirty implementation.
Kotlin
1
star
48

melody-template

Melody Starter Example
JavaScript
1
star
49

mod_whatkilledus

Copy of sources from https://emptyhammock.com/projects/httpd/diag/
C
1
star
50

TriMamba

Collection of tools aimed to gather event information from different sources into a database
JavaScript
1
star