Created
December 4, 2024 05:21
-
-
Save aleung/ad67b93affd352867792725656ac723d to your computer and use it in GitHub Desktop.
Fix errors reported by eslint rule import/exports-last
This file contains 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 { Project, Node } from 'ts-morph'; | |
const args = process.argv.slice(2); | |
const sourceFilePath = args[0]; | |
if (!sourceFilePath) { | |
console.log('Please specify the source file path.'); | |
process.exit(1); | |
} | |
const project = new Project(); | |
const sourceFile = project.addSourceFileAtPath(sourceFilePath); | |
const exportDeclarations: string[] = []; | |
// Find and remove export keywords from declarations | |
sourceFile.forEachDescendant((node) => { | |
if ( | |
Node.isInterfaceDeclaration(node) || | |
Node.isClassDeclaration(node) || | |
Node.isFunctionDeclaration(node) || | |
Node.isTypeAliasDeclaration(node) || | |
Node.isEnumDeclaration(node) || | |
Node.isVariableStatement(node) | |
) { | |
const text = node.getText(); | |
if (text.startsWith("export ")) { | |
const newText = text.substring("export ".length); | |
node.replaceWithText(newText); | |
if (Node.isVariableStatement(node)) { | |
const declarations = node.getDeclarations(); | |
declarations.forEach((declaration) => { | |
const name = declaration.getName(); | |
if (name) { | |
exportDeclarations.push(name); | |
} else { | |
console.warn("Encountered unnamed variable export. Skipping."); | |
} | |
}); | |
} else { | |
const name = node.getName(); | |
if (name) { | |
exportDeclarations.push(name); | |
} else { | |
console.warn("Encountered unnamed export. Skipping."); | |
} | |
} | |
} | |
} | |
}); | |
console.log('Export declarations:', exportDeclarations.join(",")); | |
if (exportDeclarations.length > 0) { | |
// Add export statement at the end | |
sourceFile.addExportDeclaration({ | |
namedExports: exportDeclarations | |
}); | |
} | |
sourceFile.saveSync(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment