2

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?

curiousgeorge
  • 593
  • 1
  • 5
  • 14

2 Answers2

2

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.

steoiatsl
  • 1,892
  • 2
  • 22
  • 39
  • This doesnt work. It gives the same error as in the question. I am using babel7 – Souradeep Nanda Dec 16 '19 at 08:13
  • I think this is an error with the types you're trying to insert, not the `.insertBefore()` or `.insertAfter()` functions. Just try to insert something simpler. I have a babel project, and I've used `.insertAfter()` with a node and it works. @SouradeepNanda – steoiatsl Dec 16 '19 at 23:13
  • I am trying to insert JSX. – Souradeep Nanda Dec 17 '19 at 03:26
  • Very very late. But I guess you just need to look at the link in the post. I gave it a quick look. Maybe this is what you're looking for `t.jsxAttribute(name, value);`. – steoiatsl Mar 31 '22 at 23:46
0

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>')
Souradeep Nanda
  • 3,116
  • 2
  • 30
  • 44