'Remove named imports in Typescript output
In my tsconfig.json
"target": "esnext"
"module": "esnext"
In my package.json
"type": "module"
My source files are .mts, my output is .mjs. This is the error I'm getting.
import { model, Schema } from 'mongoose';
^^^^^^
SyntaxError: Named export 'Schema' 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 { model, Schema } = pkg;
Now I understand you can't use named imports from commonjs module generally. But working with Typescript I thought there'd be a way to write named imports in my source files, and have the compiled output remove them. The problem is I don't know how.
I tried to compile my code to commonjs but I run into this problem
exports is not defined in es module scope
I suspect because my output is .mjs. I definitely don't want to switch all my project to .ts.
So is there a way to have my output not use named imports without me doing something annoying like this in my source code?
import mongoose from 'mongoose'
const someSchema = new mongoose.Schema(...)
Solution 1:[1]
No, because mongoose is still a CommonJS module, you can only import names which are set on module.exports (and there aren't any other than the mongoose module itself, which is the default export). The documentation makes this clear.
If you don't want to use a form of dot or bracket property access notation when using the properties of mongoose, then you can:
destructure the destructurable ones like this:
import mongoose from 'mongoose'; const {Schema} = mongoose; console.log(new Schema());bind ones that might depend on their
thisvalue beingmongoose:import mongoose from 'mongoose'; const Schema = mongoose.Schema.bind(mongoose); console.log(new Schema());
Note, you'll also need to set these TSConfig options:
compilerOptions.allowSyntheticDefaultImportstotrue, andcompilerOptions.moduleResolutionto"node".
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
