Created
November 5, 2023 22:00
-
-
Save empjustine/38d79ad97729f5223e7292439ae33dea to your computer and use it in GitHub Desktop.
recast sort imports
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 fs from 'node:fs'; | |
import recast from 'recast'; | |
const { namedTypes: n, builders: b } = recast.types.builders; | |
const code = fs.readFileSync(process.stdin.fd, 'utf-8'); | |
const ast = recast.parse(code); | |
const imports = ast.program.body.filter(node => n.ImportDeclaration.check(node)); | |
imports.sort((a, b) => { | |
const importA = a.source.value; | |
const importB = b.source.value; | |
return importA.localeCompare(importB); | |
}); | |
ast.program.body = imports; | |
const sortedCode = recast.print(ast).code; | |
console.log(sortedCode); |
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
{ | |
"type": "module", | |
"dependencies": { | |
"recast": "^0.23.4" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment