How can I use @babel/register (or alternative) in conjunction with native ESM in Node?

Viewed 391

I'm writing the test suite for a web app, and I need to import the JSX from the source into a test environment. Part of this process uses @babel/register to correctly transpile my JSX into standard JS. My babel config looks like the following:

{
  "presets": ["@babel/preset-env"],
  "plugins": [
    "@babel/plugin-syntax-jsx",
    ["babel-plugin-transform-jsx-to-htm",{
      "import": {
        "module": "htm/preact",
        "export": "html"
      },
      "tag": "$$html"
    }]
  ]
}

And I execute with node -r @babel/register ...<unrelated test command here>

The problem I'm running into is when one of my source files imports from a library that only offers ESM output, no CJS. Here's the error I'm met with:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: <file path to non-working ESM module>
require() of ES modules is not supported.
require() of <file path to non-working ESM module> from <file path to source that imports it> is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename <esm file>.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from <file path to non-working ESM module>/package.json.

    at Module._extensions..js (internal/modules/cjs/loader.js:1080:13)
    at Object.newLoader [as .js] (/home/ryun/Projects/foobar/node_modules/pirates/lib/index.js:104:7)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (<file path to source that imports it>.jsx:1:1)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Module._compile (/home/ryun/Projects/foobar/node_modules/pirates/lib/index.js:99:24)
    at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)

At the bottom of the docs page for @babel/register, it states: Note: @babel/register does not support compiling native Node.js ES modules on the fly, since currently there is no stable API for intercepting ES modules loading. Because of this, I figure @babel/register is a no-go, but no work around is offered. I can't figure out what I'm supposed to do there besides hard-fork that lib I'm using and have it export CJS just for the sake of my test suite.

0 Answers
Related