3
const ts = require('typescript');

let template = `
         let hello: string = 'hello,world';
`
ts.transform

How to convert strings in the above operation?

2
  • You want to use the typescript compiler to compile the string template? Commented Jan 26, 2018 at 7:07
  • Yes, I want to do this Commented Jan 26, 2018 at 7:54

1 Answer 1

2

You can use the transpile function. This will allow you to compile an arbitrary string:

import * as typescript from 'typescript';  

let template = `
         let hello: string = 'hello,world';
         class test{}
`
let errors : typescript.Diagnostic[] = []
let result = typescript.transpile(template, {}, undefined, errors);

// The result
console.log(result);
// The erorrs
for(let err of errors) console.log(err.messageText);

Edit

The solution above works, but it only checks for syntactical errors not for semantic errors. A version which does module resolution and will check for semantic errors would be:

function transpileWithAllErrors(input: string, compilerOptions?: typescript.CompilerOptions, fileName: string = "dynamic.ts", diagnostics?: typescript.Diagnostic[]): string {
    let result: string;
    let host = typescript.createCompilerHost({});
    let sourceFile = typescript.createSourceFile(fileName, template, typescript.ScriptTarget.ES5);
    let orginalGetSourceFile = host.getSourceFile;
    host.getSourceFile = (file, languageVersion, onError, shouldCreateNewSourceFile) =>
        file == fileName ?
            sourceFile :
            orginalGetSourceFile(file, languageVersion, onError, shouldCreateNewSourceFile);

    host.getCurrentDirectory = () => "";
    host.getDefaultLibLocation = () => "node_modules/typescript/lib";
    host.getDefaultLibFileName = () => "node_modules/typescript/lib/lib.d.ts";

    let program = typescript.createProgram([fileName], {}, host);

    // Capture output, 
    host.writeFile = (wFileName, data) =>{ 
        if(wFileName.endsWith(".js")) {
            result = data;
        }
    };

    if (diagnostics != null) {
        diagnostics.push(...program.getSyntacticDiagnostics(sourceFile));
        diagnostics.push(...program.getSemanticDiagnostics(sourceFile));
        diagnostics.push(...program.getOptionsDiagnostics());
    }
    program.emit(sourceFile);
    return result;
}

Usage:

let diagnostics: typescript.Diagnostic[] = []
let result = transpileWithAllErrors(template, {}, undefined, diagnostics);
for (let err of diagnostics) console.log(err.messageText);
console.log(result);

Note: This method does module resolution relative to the current path so the script has access to any modules installed in the current path. Also I did not do extensive testing on the code, but it should work.

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you,Do you know that there is a way to check for syntax errors?
@付延伟 Modified the answer to get the errors and log them
function a(c:text){console.log('aaaaaa')}, However, this passage can still be compiled smoothly,there is no “text” variables
@付延伟 Yes, transpile does not provide export semantic errors, only syntactical ones. Not sure why this is, I am looking into an alternative, but there does not seem to be one.
@付延伟 I am working on a version, I am very close, but I don't have time to finish right now. I will update the answer by tomorrow to also include semnatic errors, unfortunately, it won't be just a simple method call.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.