3
// Input
class Foo {
    templateString = 'some value';
}

// Output
import __LIB__ from '@scope/lib/path/to/lib';

class Foo {
    templateString = (function compiledTemplate(deps) {
        // ...
        return result;
    })({lib: __LIB__});
}

In fact, I have two questions:

  1. How to create AST-fragment from string?
  2. How to add import?

P.S. I tried various methods createSourceFile and ts.createImportDeclaration, but they all lead to this or that error: [

2
  • 2
    Have you tried just creating an Identifier with the appropriate text for the replacement node? In other words: createIdentifier(`(function compiledTemplate(deps) { /*...*/ }`). Commented Jun 5, 2017 at 7:43
  • It's work 0_o, but how add import lib from '@scope/lib';? Commented Jun 5, 2017 at 7:57

1 Answer 1

5

To add in arbitrary text, the best way I know of is to use createIdentifier with the string you want to insert.


To add in an import statement, remember that you're updating the tree without mutating the original.

The ts.visitEachChild API takes a nodesVisitor parameter which specially operates on NodeArrays. Usually, if you don't pass a nodesVisitor in, it will operate on each Node in the NodeArray using the first callback you pass for the visitor parameter, but here you specially want to operate on the full node array.

In your case, you're interested in a SourceFile's statements (which is a NodeArray<Statement>. You can create the import with createImportDeclaration, and update the SourceFile by passing in a nodesVisitor like the following:

function addImport(statements: ts.NodeArray<ts.Statement>) {
    const importStatement = ts.createImportStatement(/*...*/);
    return ts.createNodeArray([importStatement, ...statements]);
}

visitEachChild(
    sourceFile,
    /*replace this with something that controls traversal*/ x => x,
    context, 
    addImport);
Sign up to request clarification or add additional context in comments.

3 Comments

Alas, don't work: gist.github.com/RubaXa/…
Check out the example I gave for how to create a new node and how to call visitEachChild.
Happened, but still does not work correctly: github.com/RubaXa/typescript-api-questions/tree/master/…

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.