Skip to content

Instantly share code, notes, and snippets.

@stevebauman
Last active April 2, 2025 07:43
Show Gist options
  • Save stevebauman/a1ce0ef8ca5fb75d417a3b05f6ff2896 to your computer and use it in GitHub Desktop.
Save stevebauman/a1ce0ef8ca5fb75d417a3b05f6ff2896 to your computer and use it in GitHub Desktop.
Sort JS Imports by length using ESLint Rule (asc)
-import axios from 'axios';
-import fs from 'fs';
-import path from 'path';
-import a from 'a';
-import somethingElse from '../somethingElse';
+import a from 'a';
+import fs from 'fs';
+import path from 'path';
+import axios from 'axios';
+import somethingElse from '../somethingElse';
module.exports = {
meta: {
type: 'problem',
fixable: 'code',
},
create(context) {
return {
ImportDeclaration(node) {
const sourceCode = context.getSourceCode();
const imports = sourceCode.ast.body.filter((node) => node.type === 'ImportDeclaration');
// Bail if there is one (or no) import declarations.
if (imports.length <= 1) {
return;
}
// Sort the import lines by length.
const sortedImports = [...imports].sort((a, b) => {
const aLength = sourceCode.getText(a).length;
const bLength = sourceCode.getText(b).length;
return aLength - bLength;
});
// Check if the imports are already sorted.
if (imports.every((value, index) => value === sortedImports[index])) {
return;
}
// Report the issue and provide a fix.
context.report({
node,
message: 'Imports should be sorted by length (shortest to longest).',
fix(fixer) {
const importLines = sortedImports.map((imp) => sourceCode.getText(imp));
return fixer.replaceTextRange(
[imports[0].range[0], imports[imports.length - 1].range[1]],
importLines.join('\n')
);
},
});
},
};
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment