Skip to content

Instantly share code, notes, and snippets.

@noghartt
Created March 1, 2023 03:02
Show Gist options
  • Save noghartt/4a5de4d2832b5d831b83526ed91f87af to your computer and use it in GitHub Desktop.
Save noghartt/4a5de4d2832b5d831b83526ed91f87af to your computer and use it in GitHub Desktop.
Some example using TypeScript compiler API
import ts from 'typescript';
import { readFile, writeFile } from 'fs/promises';
const sourceText = await readFile('./input.ts', { encoding: 'utf8' });
const source = ts.createSourceFile('input.ts', sourceText, ts.ScriptTarget.Latest);
const newArticle = ts.factory.createObjectLiteralExpression(
[
ts.factory.createPropertyAssignment(
ts.factory.createIdentifier('title'),
ts.factory.createStringLiteral('New Article'),
),
ts.factory.createPropertyAssignment(
ts.factory.createIdentifier('url'),
ts.factory.createStringLiteral('New Article'),
),
],
true,
);
const transformer: ts.TransformerFactory<ts.SourceFile> = (context) => {
const visitNode = (node: ts.Node): ts.Node => {
if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'articles') {
const updatedArray = context.factory.updateArrayLiteralExpression(
node.initializer as ts.ArrayLiteralExpression,
[
newArticle,
...node?.initializer?.elements,
],
);
return context.factory.updateVariableDeclaration(node, node.name, node.exclamationToken, node.type, updatedArray);
}
return ts.visitEachChild(node, visitNode, context);
}
return (sourceFile) => ts.visitNode(sourceFile, visitNode);
}
const transformedSourceFile = ts.transform(source, [transformer]);
const printer = ts.createPrinter();
const updated = printer.printNode(
ts.EmitHint.Unspecified,
transformedSourceFile.transformed[0],
ts.createSourceFile("./output.ts", "", ts.ScriptTarget.Latest)
);
await writeFile('./output.ts', updated);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment