Last active
April 2, 2025 07:43
-
-
Save stevebauman/a1ce0ef8ca5fb75d417a3b05f6ff2896 to your computer and use it in GitHub Desktop.
Sort JS Imports by length using ESLint Rule (asc)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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