Forget alphabetical or chronological ordering, the future is in bringing aesthetic order to import and require statements 🌺
You'll first need to install ESLint:
npm i eslint --save-dev
Next, install eslint-plugin-import-order-aesthetic
:
npm install eslint-plugin-import-order-aesthetic --save-dev
As this rule is linting es6 modules, you are required to add es6
to the env
object in your .eslintrc
configuration.
You will also need to add sourceType: 'module'
to the parserOptions
object.
env: {
es6: true
},
parserOptions: {
sourceType: 'module'
}
Add import-order-aesthetic
to the plugins section of your .eslintrc
configuration file. You can omit the eslint-plugin-
prefix:
{
"plugins": ["import-order-aesthetic"]
}
Configure the rules you want to use under the rules section of your .eslintrc
configuration file:
{
"rules": {
"import-order-aesthetic/order-import-by-length": ['error', { reverseOrder: true }],
"import-order-aesthetic/order-require-by-length": ['error', { reverseOrder: false }],
}
}
Example .eslintrc.js
file:
module.exports = {
env: {
es6: true,
},
parserOptions: {
parser: "babel-eslint",
sourceType: "module",
},
plugins: ["import-order-aesthetic"],
rules: {
"import-order-aesthetic/order-import-by-length": [
"error",
{ reverseOrder: true },
],
"import-order-aesthetic/order-require-by-length": [
"error",
{ reverseOrder: false },
],
},
};
Using --fix
with your eslint
command will auto-arrange your import/require statements.
The fix functionality should work automatically with ESLint extensions in your code editor if you have it configured to fix on save etc.
Organise import statements aesthetically by ordering them according to line length and then alphabetically.
Organise require statements aesthetically by ordering them according to line length and then alphabetically.
The default behaviour of both rules rule is a 'top-heavy' order. Set reverseOrder
to true
to use a 'bottom-heavy' order.
false
(default)true
Usage:
"import-order-aesthetic/order-import-by-length": ['error', { reverseOrder: true }],
Default:
const c = require("testing");
const b = require("tester");
const a = require("test");
require("test");
Reversed:
require("test");
const a = require("test");
const b = require("tester");
const c = require("testing");
At the moment the two rules are interpreted separately so will assess import and require statements independently. If you mix these two in a single file they will be ordered as normal, but not in relation to each other.
This is on the roadmap, PRs welcome.
If you want to order your import/require statements by something sensible... :)
- Add support for mixed import & require statement (see issues).
- Potentially improve the ExpressionStatement type validation.