Как проверить тип фрагмента кода TypeScript в памяти? - PullRequest
0 голосов
/ 12 декабря 2018

Я внедряю поддержку TypeScript в свое приложение Блокнот Data-Forge .

Мне нужно скомпилировать, проверить тип и оценить фрагменты кода TypeScript.

КомпиляцияКажется, это не проблема, я использую transpileModule, как показано ниже, чтобы преобразовать фрагмент кода TS в код JavaScript, который можно оценить:

import { transpileModule, TranspileOptions } from "typescript";

const transpileOptions: TranspileOptions = {
    compilerOptions: {},
    reportDiagnostics: true,
};

const tsCodeSnippet = " /* TS code goes here */ ";
const jsOutput = transpileModule(tsCodeSnippet, transpileOptions);
console.log(JSON.stringify(jsOutput, null, 4));

Однако при попытке компиляции возникает проблемаКод TS с ошибкой.

Например, следующая функция имеет ошибку типа, но передается без какой-либо диагностики ошибок:

function foo(): string {
    return 5;
}

Прозрачность - это здорово, но я бы тожехотел бы иметь возможность отображать ошибки для моего пользователя.

Итак, мой вопрос : как это можно сделать, но также выполнять проверку типов и создавать ошибки для семантических ошибок?

Обратите внимание, что я не хочу сохранятьВведите TypeScript код в файл.Это было бы ненужным бременем производительности для моего приложения.Я хочу только скомпилировать и напечатать контрольные фрагменты кода, которые хранятся в памяти.

Ответы [ 2 ]

0 голосов
/ 30 января 2019

Я решил эту проблему, опираясь на оригинальную помощь Дэвида Шеррета, а затем совет Фабиана Пиркльбауэра ( создатель TypeScript Playground ).

Я создал прокси-сервер CompilerHostобернуть настоящий CompilerHost.Прокси-сервер способен возвращать код TypeScript в памяти для компиляции.Базовый реальный CompilerHost способен загружать библиотеки TypeScript по умолчанию.Библиотеки необходимы, иначе вы получите множество ошибок, связанных со встроенными типами данных TypeScript.

Код

import * as ts from "typescript";

//
// A snippet of TypeScript code that has a semantic/type error in it.
//
const code 
    = "function foo(input: number) {\n" 
    + "    console.log('Hello!');\n"
    + "};\n" 
    + "foo('x');"
    ;

//
// Result of compiling TypeScript code.
//
export interface CompilationResult {
    code?: string;
    diagnostics: ts.Diagnostic[]
};

//
// Check and compile in-memory TypeScript code for errors.
//
function compileTypeScriptCode(code: string, libs: string[]): CompilationResult {
    const options = ts.getDefaultCompilerOptions();
    const realHost = ts.createCompilerHost(options, true);

    const dummyFilePath = "/in-memory-file.ts";
    const dummySourceFile = ts.createSourceFile(dummyFilePath, code, ts.ScriptTarget.Latest);
    let outputCode: string | undefined = undefined;

    const host: ts.CompilerHost = {
        fileExists: filePath => filePath === dummyFilePath || realHost.fileExists(filePath),
        directoryExists: realHost.directoryExists && realHost.directoryExists.bind(realHost),
        getCurrentDirectory: realHost.getCurrentDirectory.bind(realHost),
        getDirectories: realHost.getDirectories.bind(realHost),
        getCanonicalFileName: fileName => realHost.getCanonicalFileName(fileName),
        getNewLine: realHost.getNewLine.bind(realHost),
        getDefaultLibFileName: realHost.getDefaultLibFileName.bind(realHost),
        getSourceFile: (fileName, languageVersion, onError, shouldCreateNewSourceFile) => fileName === dummyFilePath 
            ? dummySourceFile 
            : realHost.getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile),
        readFile: filePath => filePath === dummyFilePath 
            ? code 
            : realHost.readFile(filePath),
        useCaseSensitiveFileNames: () => realHost.useCaseSensitiveFileNames(),
        writeFile: (fileName, data) => outputCode = data,
    };

    const rootNames = libs.map(lib => require.resolve(`typescript/lib/lib.${lib}.d.ts`));
    const program = ts.createProgram(rootNames.concat([dummyFilePath]), options, host);
    const emitResult = program.emit();
    const diagnostics = ts.getPreEmitDiagnostics(program);
    return {
        code: outputCode,
        diagnostics: emitResult.diagnostics.concat(diagnostics)
    };
}

console.log("==== Evaluating code ====");
console.log(code);
console.log();

const libs = [ 'es2015' ];
const result = compileTypeScriptCode(code, libs);

console.log("==== Output code ====");
console.log(result.code);
console.log();

console.log("==== Diagnostics ====");
for (const diagnostic of result.diagnostics) {
    console.log(diagnostic.messageText);
}
console.log();

Вывод

==== Evaluating code ====
function foo(input: number) {
    console.log('Hello!');
};
foo('x');
=========================
Diagnosics:
Argument of type '"x"' is not assignable to parameter of type 'number'.

Полный рабочий пример доступен на моем Github .

0 голосов
/ 13 декабря 2018

Ситуация 1 - Использование только памяти - Нет доступа к файловой системе (например, в Интернете)

Это непростая задача, которая может занять некоторое время.Возможно, есть более простой способ, но я еще не нашел.

  1. Реализация ts.CompilerHost, где такие методы, как fileExists, readFile, directoryExists, getDirectories() и т. Д.. читать из памяти вместо фактической файловой системы.
  2. Загрузить соответствующие lib файлы в вашу файловую систему в памяти в зависимости от того, что вам нужно (например, lib.es6.d.ts или lib.dom.d.ts ).
  3. Добавьте также файл в памяти в файловую систему в памяти.
  4. Создатьзапрограммируйте (используя ts.createProgram) и передайте пользовательский ts.CompilerHost.
  5. . Вызовите ts.getPreEmitDiagnostics(program), чтобы получить диагностику.

Несовершенный пример

Вот краткий несовершенный пример, который неправильно реализует файловую систему в памяти и не загружает файлы lib (поэтому будут глобальные диагностические ошибки ... они могут быть проигнорированы или вы можете вызывать определенные методы на program кроме program.getGlobalDiagnostics(). Обратите внимание на поведение ts.getPreEmitDiagnostics здесь ):

import * as ts from "typescript";

console.log(getDiagnosticsForText("const t: number = '';").map(d => d.messageText));

function getDiagnosticsForText(text: string) {
    const dummyFilePath = "/file.ts";
    const textAst = ts.createSourceFile(dummyFilePath, text, ts.ScriptTarget.Latest);
    const options: ts.CompilerOptions = {};
    const host: ts.CompilerHost = {
        fileExists: filePath => filePath === dummyFilePath,
        directoryExists: dirPath => dirPath === "/",
        getCurrentDirectory: () => "/",
        getDirectories: () => [],
        getCanonicalFileName: fileName => fileName,
        getNewLine: () => "\n",
        getDefaultLibFileName: () => "",
        getSourceFile: filePath => filePath === dummyFilePath ? textAst : undefined,
        readFile: filePath => filePath === dummyFilePath ? text : undefined,
        useCaseSensitiveFileNames: () => true,
        writeFile: () => {}
    };
    const program = ts.createProgram({
        options,
        rootNames: [dummyFilePath],
        host
    });

    return ts.getPreEmitDiagnostics(program);
}

Ситуация 2 - доступ к файлу system

Если у вас есть доступ к файловой системе, это намного проще, и вы можете использовать функцию, аналогичную приведенной ниже:

import * as path from "path";

function getDiagnosticsForText(
    rootDir: string,
    text: string,
    options?: ts.CompilerOptions,
    cancellationToken?: ts.CancellationToken
) {
    options = options || ts.getDefaultCompilerOptions();
    const inMemoryFilePath = path.resolve(path.join(rootDir, "__dummy-file.ts"));
    const textAst = ts.createSourceFile(inMemoryFilePath, text, options.target || ts.ScriptTarget.Latest);
    const host = ts.createCompilerHost(options, true);

    overrideIfInMemoryFile("getSourceFile", textAst);
    overrideIfInMemoryFile("readFile", text);
    overrideIfInMemoryFile("fileExists", true);

    const program = ts.createProgram({
        options,
        rootNames: [inMemoryFilePath],
        host
    });

    return ts.getPreEmitDiagnostics(program, textAst, cancellationToken);

    function overrideIfInMemoryFile(methodName: keyof ts.CompilerHost, inMemoryValue: any) {
        const originalMethod = host[methodName] as Function;
        host[methodName] = (...args: unknown[]) => {
            // resolve the path because typescript will normalize it
            // to forward slashes on windows
            const filePath = path.resolve(args[0] as string);
            if (filePath === inMemoryFilePath)
                return inMemoryValue;
            return originalMethod.apply(host, args);
        };
    }
}

// example...
console.log(getDiagnosticsForText(
    __dirname,
    "import * as ts from 'typescript';\n const t: string = ts.createProgram;"
));

При этом компиляторнайдите в указанной rootDir папке node_modules и используйте набранные там символы (их не нужно загружать в память каким-либо другим способом).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...