Babel Plugin: How to insert a sibling node

1.8k views Asked by At

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?

2

There are 2 answers

4
842Mono On

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.

0
Souradeep Nanda On

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>')