babel-plugin-validate-jsx-nesting

Babel plugin to validate JSX nesting at compile time

When browsers encounter invalid nesting like <hr> inside <p>, they silently fix the DOM structure - causing mismatches between your JSX and the actual DOM.

Markup

<p>
  hello
  <hr/>
</p>

Browser modifies it to this:

<p>hello</p>
<hr />
<p></p>

This babel plugin catches these errors at compile time:

Failed to Compile.

Error: Invalid HTML nesting: <hr> can not be child of <p>
  1 | <p>
  2 |   <span> Hello </span>
> 3 |   <hr />
    |   ^^^^^^
  4 |   <span> World </span>
  5 | </p>

Setup

Install the babel-plugin-validate-jsx-nesting package and add it to the plugins section of your babel configuration file.

{
  "plugins": ["validate-jsx-nesting"]
}

Use warnOnly to log warnings instead of failing the build.

{
  "plugins": [["validate-jsx-nesting", { "warnOnly": true }]]
}

Related