curiousgeorge
curiousgeorge

Reputation: 619

Babel Plugin: How to insert a sibling node

It seems that path.insertAfter(), path.insertBefore(), path.unshiftContainer(), and path.pushContainer() only work with Statements. How do you insert nodes that are not Statements?

In my case I am writing a babel jsx plugin and I am trying to insert a sibling node which is a JSXExpressionContainer. When I do this I get the following error:

TypeError: Property body[0] of BlockStatement expected node to be of a type ["Statement"] but instead got "JSXExpressionContainer"

How do I fix this?

Upvotes: 2

Views: 2040

Answers (2)

842Mono
842Mono

Reputation: 1988

From the documentation here:

FunctionDeclaration(path) {
  path.insertBefore(t.expressionStatement(t.stringLiteral("Because I'm easy come, easy go.")));
  path.insertAfter(t.expressionStatement(t.stringLiteral("A little high, little low.")));
}

Looking at your error, make sure you do your types correctly. Just check babel types here and see what parameters are needed by each type.

Upvotes: 2

Souradeep Nanda
Souradeep Nanda

Reputation: 3298

I found a workaround by just pushing the code as plaintext. React seems to work just fine.

path.node.children.push('<div>Click me</div>')

Upvotes: 0

Related Questions