A prettier plugin to sort imports in typescript and javascript files by the provided RegEx order.
No Data
A prettier plugin to sort import declarations by provided RegEx order.
npm
shell script npm install --save-dev @trivago/prettier-plugin-sort-imports
or, using yarn
shell script yarn add --dev @trivago/prettier-plugin-sort-imports
Add an order in prettier config file.
ecmascript 6 module.exports = { "printWidth": 80, "tabWidth": 4, "trailingComma": "all", "singleQuote": true, "jsxBracketSameLine": true, "semi": true, "importOrder": ["^@core/(.*)$", "^@server/(.*)$", "^@ui/(.*)$", "^[./]"], "importOrderSeparation": true, }
importOrder
A collection of regular expressions in string format. The plugin uses
new RegExpto evaluate regular expression. E.g.
node.source.value.match(new RegExp(val))Here,
valis the string provided in import order.
importOrderSeparation
A boolean value to enable or disable the new line separation between sorted import declarations. The separation takes place according to
importOrder.
The plugin extracts the imports which are defined in
importOrder. These imports are local imports. The imports which are not part of the
importOrderis considered as 3rd party imports.
After, the plugin sorts the local imports and 3rd party imports using natural sort algorithm. In the end, the plugin returns final imports with 3rd party imports on top and local imports at the end.
importOrderlist ?
You can define the RegEx in the
importOrder. For example if you want to sort the following imports:
ecmascript 6 import React from 'react'; import classnames from 'classnames'; import z from '@server/z'; import a from '@server/a'; import s from './'; import p from '@ui/p'; import q from '@ui/q';then the
importOrderwould be
["^@ui/(.*)$","^@server/(.*)$", '^[./]']. Now, the final output would be as follows:
ecmascript 6 import classnames from 'classnames'; import React from 'react'; import p from '@ui/p'; import q from '@ui/q'; import a from '@server/a'; import z from '@server/z'; import s from './';
There is a examples directory. The examples file can be formatted by using
npm run examplecommand.
shell script npm run example examples/example.tsx
| Ayush Sharma | Behrang Yarahmadi
|---|---|
| |
| @ayusharma_ | @behrang_y