Closed novemberborn closed 3 years ago
I'm unable to import es module https://github.com/HydreIO/rgraph (which provides no cjs) using ava with babel.
Ava Config:
{
"babel": true,
"extensions": [
"ts"
],
"require": [
"ts-node/register"
],
"files": [
"test/**/*.spec.ts"
]
}
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /project/node_modules/@hydre/rgraph/src/index.js
require() of ES modules is not supported.
require() of /project/node_modules/@hydre/rgraph/src/index.js from /project/server/lib/database.ts 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 index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /project/node_modules/@hydre/rgraph/package.json.
› Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /project/node_modules/@hydre/rgraph/package.json.
› Object.<anonymous> (lib/database.ts:2:1)
› Module.m._compile (/project/node_modules/ts-node/src/index.ts:1043:23)
─
Is this the correct issue for this error?
Is this the correct issue for this error?
No, this is about support ESM modules in AVA's require
option.
@FallingSnow you seem to be mixing a Babel setup with t-node
… and possibly using AVA 2? ts-node
will use CJS, so you're probably compiling your TypeScript down to that. Which means you need to explicitly use import()
to load rgraph
and that'll be asynchronous and therefore annoying.
I suggest you figure out how to make this work outside of AVA and then use that insight to make your tests work. And yes you'd think this would all just work out of the box but ESM is actually still very new within Node.
I figured it out using #2540. It worked outside of AVA, but I found out that inside AVA, type: "module"
only applies to .js files.
Also wanna point out I'm not using babel and am on AVA 3.
Final config ended up being the following.
"ava": {
"extensions": {
"ts": "module"
},
"nonSemVerExperiments": {
"configurableModuleFormat": true
},
"nodeArguments": [
"--loader=ts-node/esm",
"--experimental-specifier-resolution=node"
],
"files": [
"test/**/*.spec.ts"
]
}
I believe this is now supported in AVA 4.
https://github.com/avajs/ava/issues/2344 will enable us to load
.mjs
dependencies through therequire
configuration. However it doesn't help usimport()
packages that cannot berequire()
d.We need to come up with a mechanism for detecting or configuring the loading of such packages.