Skip to content

Instantly share code, notes, and snippets.

@AlexGeb
Last active April 9, 2026 10:49
Show Gist options
  • Select an option

  • Save AlexGeb/e0b4e7d0d528cd2736d0ce77ad7988f3 to your computer and use it in GitHub Desktop.

Select an option

Save AlexGeb/e0b4e7d0d528cd2736d0ce77ad7988f3 to your computer and use it in GitHub Desktop.
Organize imports using ts-morph
import path from "path";
import { type FormatCodeSettings, Project } from "ts-morph";
const packageName = "assistant";
const formatSettings: FormatCodeSettings = {
ensureNewLineAtEndOfFile: true,
indentSize: 2,
};
const project = new Project({
tsConfigFilePath: path.resolve("tsconfig.json"), // root tsconfig with references
skipAddingFilesFromTsConfig: true,
});
project.addSourceFilesFromTsConfig(
path.resolve(`packages/${packageName}/tsconfig.json`),
);
const sourceFiles = project.getSourceFiles(
`packages/${packageName}/src/**/*{.ts,.tsx}`,
);
console.log("Organizing imports in", sourceFiles.length, "files...");
function chunks<T>(xs: T[], size: number): T[][] {
if (size <= 0) return [];
const chunks: T[][] = [];
for (let i = 0; i < xs.length; i += size) {
chunks.push(xs.slice(i, i + size));
}
return chunks;
}
const thunks = chunks(sourceFiles, 50).map(
(files) => () =>
Promise.all(
files.map(async (file) => {
file.organizeImports(formatSettings, {
organizeImportsTypeOrder: "first",
});
await file.save();
}),
),
);
for (const task of thunks) {
await task();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment