In my setup, I have an express server built in TypeScript with the
"module": "es2020"
configuration set in its tsconfig.
Additionally, I have created another module for my GraphQL API also utilizing TypeScript and targeting es2020
. This module interacts with mongoose using named imports:
import { Types } from 'mongoose'
While everything functions as expected when compiling the GraphQL module with tsc
, the issue arises when running the express server with:
nodemon --watch './**/*.ts' --exec 'node --experimental-specifier-resolution=node --loader ts-node/esm' src/index.ts
The express server fails to handle the mongoose named import.
import { Types } from 'mongoose';
^^^^^
SyntaxError: Named export 'Types' not found. The requested module 'mongoose' 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 'mongoose';
const { Types } = pkg;
Possible Fix #1
import mongoose from 'mongoose'
This entails replacing instances of Types
with mongoose.Types
.
Even though tsc
handles the mongoose named import successfully, it's reasonable to assume that ts-node should also have this capability.
Possible Fix #2
An alternate approach would be shifting to commonjs
. While I could retain the current import/export syntax within my GraphQL module and compile it as a cjs module, I'd be required to adopt cjs syntax in the express server - a scenario I prefer to avoid.