Skip to content

Instantly share code, notes, and snippets.

@zecka
Created September 23, 2025 13:02
Show Gist options
  • Save zecka/474ae18ad09300d867687355761dc7c7 to your computer and use it in GitHub Desktop.
Save zecka/474ae18ad09300d867687355761dc7c7 to your computer and use it in GitHub Desktop.
tsc programmatic
// build.js
import ts from "typescript";
import path from "path";
async function build() {
const projectDir = path.resolve("./packages/ds-tokens");
const configPath = path.join(projectDir, "tsconfig.build.json");
// 1. Charger tsconfig
const configFile = ts.readConfigFile(configPath, ts.sys.readFile);
if (configFile.error) {
throw new Error(ts.formatDiagnosticsWithColorAndContext([configFile.error], {
getCurrentDirectory: ts.sys.getCurrentDirectory,
getCanonicalFileName: f => f,
getNewLine: () => "\n",
}));
}
// 2. Parser la config et override l'outDir
const parsed = ts.parseJsonConfigFileContent(
{
...configFile.config,
compilerOptions: {
...configFile.config.compilerOptions,
outDir: "dist/foo", // override ici
},
},
ts.sys,
projectDir
);
// 3. Créer le programme et compiler
const program = ts.createProgram(parsed.fileNames, parsed.options);
const emitResult = program.emit();
// 4. Collecter les erreurs éventuelles
const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
if (allDiagnostics.length > 0) {
const formatHost = {
getCanonicalFileName: path => path,
getCurrentDirectory: ts.sys.getCurrentDirectory,
getNewLine: () => "\n",
};
console.error(
ts.formatDiagnosticsWithColorAndContext(allDiagnostics, formatHost)
);
}
if (emitResult.emitSkipped) {
throw new Error("❌ Compilation échouée");
}
console.log("✅ Compilation réussie");
}
// tu peux await car c’est dans une async
build().catch(err => {
console.error(err);
process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment