typescriptmocha.jses6-modulestypegoose

Mocha fails with "named export 'Ref' not found" error with Typegoose when using ESM


I have a project written in TypeScript with ESM. Some of it uses Typegoose. The project codebase builds fine and runs perfectly, but Mocha fails to run tests with this error:

SyntaxError: Named export 'Ref' not found. The requested module '@typegoose/typegoose' is a CommonJS module, which may not support all module.exports as named exports. CommonJS modules can always be imported via the default export, for example using:

import pkg from '@typegoose/typegoose'; const { modelOptions, prop, plugin, getModelForClass, Ref, } = pkg;

It doesn't matter if I use the alternate method of importing, I still get an error about Ref not being found. This is the only Typegoose piece I have issues with. If I don't use Ref Mocha has no issues testing any of the other code that depends on Typegoose.

tsconfig.json has the following set:

"module": "esnext"
"moduleResolution": "node"

package.json has the following set:

"type": "module",

.mocharc.jsonc has the following set:

  "node-option": ["experimental-specifier-resolution=node", "loader=ts-node/esm"],

Does anyone know how to resolve this issue? Since the code runs fine outside of Mocha I assume it is some sort of configuration thing I'm missing, but I can't figure out what it might be.


Solution

  • Ok, with the help of the Typegoose folks I figured out the cause: my tsconfig.json specified "transpileOnly" as true, which was causing the type to incorrectly get imported. Turning "transpileOnly" to false fixed the problem.