I have an express server written in typescript with "module": "es2020"
in its tsconfig.
I've also developed another es2020
module for my graphql API, still in typescript, and this module uses mongoose with such named imports:
import { Types } from 'mongoose'
Everything works fine when I compile my graphql module with tsc
. But the express server which is ran with
nodemon --watch './**/*.ts' --exec 'node --experimental-specifier-resolution=node --loader ts-node/esm' src/index.ts
is unable 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;
Solution #1
import mongoose from 'mongoose'
And replace Types
by mongoose.Types
.
But since tsc
can handle the mongoose named import, I have hope that it's also possible to make ts-node able to do so.
Solution #2
Switch to commonjs
, I can keep the import/export syntax in my graphql module and compile it as a cjs module. But I would have to use a cjs syntax in my express server, and I don't want to.
@types/mongodb
to my module won't make me able to use mongoose named import with ts-node, btw I'm not only importingTypes
from mongoose, in some other files I'm importingSchema
andModel
. And I'm facing the same error – Daileytsc
before running it with node, which works fine, but I have to rebuild and start the server after each modification – Dailey