The export named 'Types' was not located. The module 'mongoose' that was requested is a CommonJS module, which may not fully support all module.exports as named exports

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.

Answer №1

Summary:

To simplify, just take out the curly braces from the Types when importing. This should resolve the issue. Here is an example:

import Types from 'mongoose'

Note that the specific name used for Types is not crucial.

Explanation:

The code import Types from 'mongoose' functions because it retrieves the package's default export (which explains why the variable name can be anything).

In contrast, using

import * as Types from 'mongoose'
implies a desire for everything in its original form. This means rather than receiving the default export:

{
    "function1": {},
    "function2": {}
}

You will actually receive:

{
    "default": {
        "function1": {},
        "function2": {}
    }
}

Therefore, you could technically access this by using Types.default, although this may not be the most elegant solution. 🙂

A helpful reference found on StackOverflow explains how to make both approaches function, but also highlights potential drawbacks of using a workaround like this 😓

Answer №2

If you come across this issue while working with a mono-repo, ensure that the problematic module includes

"type": "module" 

in its package.json.

It appears that Nodejs assumes packages are using commonjs by default, so you must specify that your package is a module.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript array error - unrecognized symbol

Hello, I am attempting to generate an array of errors and showcase them all at once. Here is my code: if (!first_name) { var error[] = "Please fill in the Last Name"; $('#first_name').addClass('error'); } else { $('#fi ...

Is it possible to display a thumbnail image in a separate full-sized window by using CSS or JavaScript?

I am currently utilizing a program called WebWorks 2020.1 that automatically creates <img> tags from my FrameMaker source input when published to DHTML. Unfortunately, I do not have the ability to directly modify the HTML <img> or <a> tag ...

Struggling to make npm and sqlite3 function properly on MacOS Catalina

Struggling with npm package installation in a project directory on my Mac has proven to be quite the challenge. Each attempt at a simple npm install results in perplexing errors that I can't seem to grasp. The hurdle seems to center around specific p ...

Tips for accurately documenting the Props parameter in a React component with Destructuring assignment

Attempting to create JSDocs for a React component using destructuring assignment to access props: const PostComponent: React.FC<IPostComponent> = ({ title, body }) => { ... } The issue arises when trying to document multiple parameters in JSDocs ...

Calculate the total sum of input values using jQuery

Here is the HTML I've been working with: I am trying to create a script where one textbox will display the total amount, and another textbox will display the following data: "name": [{ "id": 3, "qty": 2 }, { "id": 4, "qty": 5 }] Here's ...

My table is only recording the last row when I add an onclick function to each row

I have a table in my html file with 3 rows. I am attempting to dynamically add the onclick method to each row during the window's onload event, which should display an alert with the clicked row index. However, no matter where I click, it always retur ...

Troubleshooting: Unusual Page Loaded on Webpack Dev Server

While working with web pack, I encountered an issue when trying to run the npm run build:dev script. Instead of seeing the actual website, I was presented with a strange page displaying my workspace folders: https://i.sstatic.net/mBNKg.png In case it&apos ...

What is causing these dynamic carousels to malfunction in Chrome?

After using Agile Carousel successfully for a while, I am now experiencing issues with it not working properly in Safari and Chrome, although it functions fine on Firefox and Safari for iPad. On this specific page, the carousel stops at the second image, ...

Enhance React component props for a styled component element using TypeScript

Looking to enhance the properties of a React component in TypeScript to include standard HTML button attributes along with specific React features such as ref. My research suggests that React.HTMLProps is the ideal type for this purpose (since React.HTMLA ...

In my Cordova application, I am able to print the locally stored JSON array, but I am encountering an issue where the

Hello, I'm having some difficulties with JSON as a beginner. I've tried searching extensively but haven't found a solution that works for me. My issue arises when attempting to save data using local storage in JSON format - the array prints ...

Date Object Replacement Error: "this is not a valid Date object."

For my web application, I require a specific date value. I attempted to modify the Date prototype, but encountered an issue with Jquery Date recognizing it. InitDate = Date; InitDate.prototype = Date.prototype; Date = function () { if (arguments.leng ...

The v-model in the Vue data() object input is not functioning properly and requires a page refresh to work correctly

Explaining this situation is quite challenging, so I created a video to demonstrate what's happening: https://www.youtube.com/watch?v=md0FWeRhVkE To break it down: A new account can be created by a user. Upon creation, the user is automatically log ...

Sorting in Ag-grid is not functioning as intended for AM/PM time formats

My goal is to display a list of schedules in either ascending or descending order. While Ag-grid provides default sorting, it doesn't align with my desired outcome after formatting the times into AM/PM format (for instance, 01:00 PM appearing before 1 ...

Why is it impossible to nest schemas without using an array?

Can anyone explain why mongoose schema definitions don't allow something like this: var NameSchema = new mongoose.Schema({ first: {type: String, trim: true }, last: {type: String, trim: true } }); var UserSchema = new mongoose.Schema({ name: N ...

Error 404 encountered while attempting to delete a MongoDB document using the combination of Express, Mongoose,

Just starting out with the MEAN stack and I have a question. So far, I've grasped the basics of adding data to mongodb using mongoose, express, and ui-router. However, I'm stuck on how to delete a document. Every time I attempt it, I encounter 40 ...

How come the value passed to the component props by getServerSideProps is incorrect?

I have been facing an issue while trying to retrieve data from 4 different endpoints and then passing them as props using getServerSideProps in Next.js. Even though the "courses" variable returned from getServerSideProps does contain the necessary course ...

Waiting for the response of a Javascript function

I have the code snippet below: myFunc(); bar(); The function myFunc() initiates an ajax request. I want to ensure that bar() is only executed after myFunc()'s ajax request has been completed. However, I do not wish to move the call to bar() inside ...

Is there a way to ensure that a promise is only executed once the previous promise has been resolved?

How can I make 2 HTTP requests in AngularJS where the second request is only executed after the first one has been resolved? Also, I need both requests' returns simultaneously. What is the best approach for achieving this? I attempted to tackle this ...

Creating JQuery UI Tabs using dynamically generated DIV elements

I'm currently in the process of developing an information dashboard that will display the outcomes of various actions within a web application. My goal is to present the data in tables, organized by tabs. Each tab will represent a different category ...

Deciphering the intricate mechanics behind _.bind

This block of code is an excerpt from the Underscore library, specifically showcasing the implementation of the _.bind function. However, I am struggling to comprehend the purpose behind modifying the prototype of an empty function. var customConstruc ...