Skip to content

Instantly share code, notes, and snippets.

@smhg
Last active January 17, 2022 14:36
Show Gist options
  • Save smhg/9e75eee75818e09f99011e565340f45f to your computer and use it in GitHub Desktop.
Save smhg/9e75eee75818e09f99011e565340f45f to your computer and use it in GitHub Desktop.
mocha esm jsx

Mocha tests containing JSX with ESM

Having a Mocha test suite containing JSX which you converted to ESM (aka import/export), you might run into

Unexpected token '<'

or

require is not defined in ES module scope, you can use import instead

depending on where you started and how far you got.

The idea is to transpile only JSX to JS as everything else is now basically covered natively in node. Pre-ESM Mocha's --require @babel/register would probably do this for you. But once you add "type": "module" to package.json it doesn't work anymore.

Solution

  • install @node-loader/babel
  • run Mocha with --loader=@node-loader/babel (or --node-option loader=@node-loader/babel from an npm workspace)

Thoughts

  • This feels like a shortcomming in Mocha's --require but is actually an issue in Babel's @babel/register. See the note at the bottom of the docs.
  • It would be great if Babel would have an official "Node loader" (node --loader) to replace the @node-loader/babel dependency.
  • Or an independent JSX-transpiler?
@qntm
Copy link

qntm commented Jan 16, 2022

Thank you so much for this information, it took me a lot of work to find this page and figure out why Mocha+JSX+ES modules wouldn't work properly for me.

@smhg
Copy link
Author

smhg commented Jan 17, 2022

Great it could help you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment