TypeScript Compiler API שימוש מתקדם ודוגמאות

ה-API של TypeScript Compiler מספק כלים רבי עוצמה לאינטראקציה פרוגרמטית עם קוד TypeScript. זה מאפשר למפתחים לנתח, לשנות וליצור קוד TypeScript בדרכים מתוחכמות. מאמר זה מתעמק בתרחישי שימוש מתקדמים ובדוגמאות כדי להמחיש את היכולות של ה-API של TypeScript Compiler.

תחילת העבודה עם TypeScript Compiler API

לפני הצלילה לשימוש מתקדם, חיוני להגדיר את ה-API של TypeScript Compiler. זה כולל התקנת TypeScript וכתיבת סקריפט בסיסי לאינטראקציה עם ה-API.

import * as ts from 'typescript';

const sourceCode = `let x: number = 1;`;
const sourceFile = ts.createSourceFile('example.ts', sourceCode, ts.ScriptTarget.ES2015);

console.log(sourceFile.text);

ניתוח קוד TypeScript

ה-API של מהדר מאפשר לנתח קוד TypeScript לעץ תחביר מופשט (AST). זה יכול להיות שימושי עבור ניתוח קוד ומשימות טרנספורמציה.

const sourceFile = ts.createSourceFile('example.ts', sourceCode, ts.ScriptTarget.ES2015);

function visit(node: ts.Node) {
  if (ts.isVariableDeclaration(node)) {
    console.log(`Variable name: ${node.name.getText()}`);
  }
  ts.forEachChild(node, visit);
}

visit(sourceFile);

שינוי קוד TypeScript

ה-API מספק כלים להמרת קוד TypeScript. דוגמה זו מראה כיצד להשתמש בשנאי כדי לשנות קוד.

function transformer<T extends ts.Node>(context: ts.TransformationContext) {
  function visit(node: T): T {
    if (ts.isVariableDeclaration(node)) {
      return ts.updateVariableDeclaration(node, node.name, node.type, ts.createLiteral(42)) as T;
    }
    return ts.visitEachChild(node, visit, context);
  }
  return (rootNode: T) => ts.visitNode(rootNode, visit);
}

const result = ts.transform(sourceFile, [transformer]);
const printer = ts.createPrinter();
const transformedCode = printer.printFile(result.transformed[0] as ts.SourceFile);

console.log(transformedCode);

יצירת קוד TypeScript

יצירת קוד TypeScript באופן פרוגרמטי היא תכונה חזקה נוספת של ה-API. הנה דוגמה כיצד ליצור קובץ TypeScript חדש מאפס.

const newSourceFile = ts.createSourceFile(
  'newFile.ts',
  `const greeting: string = 'Hello, TypeScript!';`,
  ts.ScriptTarget.ES2015
);

const printer = ts.createPrinter();
const newCode = printer.printFile(newSourceFile);

console.log(newCode);

טיפול באבחון ושגיאות

ה-API של Compiler מספק מנגנונים לטיפול באבחון ושגיאות. דוגמה זו מדגימה כיצד להשתמש באבחון כדי לדווח על בעיות בקוד TypeScript.

const program = ts.createProgram(['example.ts'], {});
const diagnostics = ts.getPreEmitDiagnostics(program);

diagnostics.forEach(diagnostic => {
  const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
  console.log(`Error: ${message}`);
});

מַסְקָנָה

ה-API של TypeScript Compiler מציע קבוצה עשירה של תכונות לעבודה עם קוד TypeScript באופן פרוגרמטי. על ידי שליטה ביכולות המתקדמות הללו, מפתחים יכולים ליצור כלים רבי עוצמה לניתוח, טרנספורמציה והפקה של קוד TypeScript, מה שמוביל לתהליכי עבודה יעילים וגמישים יותר של פיתוח.