Creating a setup in TypeScript to enable imports between CommonJS and ES modules (for node-fetch and Express)

I'm facing a challenge in trying to integrate two libraries into a single project: fetch-node, an ES module, and Express, which follows the CommonJS format. The issue arises from needing to import fetch-node using:

import fetch from 'node-fetch';

while Express requires me to import it differently:

const express = require('express')

This becomes problematic due to my configuration in package.json:

"type": "module",
and tsconfig.json:

"target": "es2016",   
"lib": ["es2019"],    
"module": "Node16",    
"esModuleInterop": true,

Attempting to import Express as mentioned above leads to this error:

const express = require('express');
                ^

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/mnt/c/Users/Johannes/citygmlToGltf/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///mnt/c/Users/Johannes/citygmlToGltf/bin/app.js:15:17
    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)

Node.js v19.1.0
error Command failed with exit code 1.

Is there a workaround for this situation? Can these two libraries not be used together effectively within a single project?

Answer №1

The issue I encountered was related to the tsconfig file. To solve it, I needed to include:

"moduleResolution": "node", 

This allowed me to utilize both require() and dynamic imports such as import * from "asdf"

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

Detect errors in the `valueChanges` subscription of Firestore and attempt a retry if an error occurs

My Angular app utilizes Firestore for storing data. I have a service set up to retrieve data in the following way: fetchCollectionColors(name) { this.db.collectionGroup('collection-colors', ref => ref.where('product', '==&ap ...

Automatically feed information to Express's partial views

Currently, I am working on an Express 4 application and utilizing twig.js as the view engine. Although I am comfortable with using twig.js, I am open to exploring other options. My experience lies in PHP/Laravel development where I have used view composer ...

Is it necessary to validate the variables once more in the router.get method even after validating them in the router.use method?

My current setup involves Node.js, Express framework, and MySQL as the database I am currently validating data within the 'use' method However, I am unsure if I should re-validate the data in the 'get' method? Here is a snippet of my ...

The issue with Mongoose not saving the modified document persists

Recently delving into Node.js, I embarked on creating a simple blog using Express, MongoDB, and Mongoose to manage post creation, editing, and deletion. While everything is running smoothly, there's an issue with the edit functionality. Below are my r ...

Deleting a file from the assets folder in Angular for good

I am attempting to permanently delete a JSON file from the assets folder using my component. Despite trying to use HttpClient, I encounter no errors but the file remains undeleted. constructor(http: HttpClient){} remove() { this.http.delete('assets ...

How to add multiple entries using Node.js and Tedious

I am currently working with an array of customer objects that I need to insert into a SQL database. These customer objects are retrieved from the request data. For this task, I am utilizing Tedious for handling the request and Tedious Connectionpool to ma ...

Utilize the Mongoose framework to incorporate the " _id" field from MongoDB into the projection

I'm working on retrieving a Mongo document using Node.js and Mongoose in the following manner: var app = express(); var Thread = mongoose.model('threads', schema); app.get('/api/closed/all', function(req, res) { Thread.find({ ...

The npx documentation explicitly states that in order to avoid any conflicts, it is essential to configure all flags and options before specifying any positional arguments. But what exactly does this directive entail?

The official npx documentation explains the differences between using npx and npm exec. npx vs npm exec When utilizing the npx binary, it is crucial to set all flags and options before including any positional arguments. On the other hand, if you run it v ...

Deactivating the drag feature when setting the duration of a new event in FullCalendar

Hello there! I've integrated full calendar into my Angular project and I'm facing a challenge. I want to restrict users from defining the duration of an event by holding click on an empty schedule in the weekly calendar, where each date interval ...

Unlock the npm package on TFS

Encountering an issue with a npm package called tfs-unlock while using grunt. Upon trying to build, the server returns the following error message: [exec] [4mRunning "tfs-unlock:checkout" (tfs-unlock) task[24m [exec] [31m>> [39mChild process exi ...

Ways to fix the error message 'yarn package has unresolved peer dependency'

Whenever I run yarn upgrade or install, a bunch of warnings pop up due to unmet peerDependencies. warning " > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4322332c2f2f2c6e2f2a2d286e2b37373303726d766d7a">[email pro ...

What is the proper way to integrate helmet.js with typescript?

Utilizing helmet from pure JavaScript according to the documentation is quite straightforward: const express = require('express') const helmet = require('helmet') const app = express() app.use(helmet()) However, I'm unsure how ...

Encountering HTML content error when attempting to log in with REST API through Express on Postman

I'm currently in the process of developing a basic login API using Node.js and Express. However, I've encountered an error when testing with Postman: <!DOCTYPE html> <html lang="en"> <head> <meta charse ...

How to start Angular2 prototype with an object literal

export abstract class GridColumn { public field?: string; public sortField?: string; public header?: string; public footer?: string; public sortable?: any = true; public editable?: boolean = false; public filter?: boolean = true ...

I am interested in subscribing to a topic on an MQTT broker with Azure IoT Hub. My goal is to have the data stored in Azure IoT Hub whenever I publish my topic

Recently, I delved into the world of MQTT and am currently in the process of configuring a MQTT protocol to transmit data from gateway devices to Azure IoT Hub. However, I am encountering an issue - I can't figure out the best method to receive and st ...

Enhancing the appearance of a JSX component in React

I have a segment of code within my project that calculates a specific percentage and displays it on the dashboard. <text className="netProfit-circle-text" x="50%" y="50%" dy=".2em" textAnchor="middl ...

When attempting to send emails, SendGrid encounters an error and fails to provide an error code

Earlier today, I successfully sent out a series of emails using SendGrid. It was quite a large number of emails, as I needed to create multiple user accounts with attached email addresses. Thankfully, everything went smoothly and all the emails were delive ...

Integrating JavaScript into HTML pages with corresponding file names

I am looking for a way to dynamically insert a .js file into an HTML page with the same filename using gulp-inject (for example, injecting index.min.js into index.html and data.min.js into data.html). The minified files are located in build/js and the HTML ...

What is causing the addListener function in the events class to malfunction?

I am a beginner in the world of node.js and attempting to execute this piece of code: var eventlib= require('events'); var emitter= new eventlib(); eventlib.addListener('MessageEvent', function() { console.log('Registered the ...

Issue with PlayWright HTML report not being served in a Docker container

I am currently executing my PlayWright tests from a docker container to validate my ReactJS application Everything is functioning as expected, and a report directory is created successfully In the event that some tests fail, PlayWright attempts to disp ...