When using TypeScript, default imports can only be done with the 'esModuleInterop' flag enabled

Below is my current code snippet in index.ts:

import { User } from "./datatypes"
import express from 'express';

 console.log("hello world")

Displayed is the content of my package.json:

{
  "name": "simple_app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "tsc index.ts && node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.0.0",
    "express": "^4.17.3"
  },
  "devDependencies": {
    "@types/express": "^4.17.13",
    "@types/node": "^17.0.23",
    "ts-node": "^10.7.0",
    "typescript": "^4.6.3"
  }
}

In addition, here is my configuration file tsconfig.json:

{
    "compilerOptions": {
      "module": "commonjs",
      "esModuleInterop": true,
      "resolveJsonModule": true,
      "target": "es6",
      "moduleResolution": "node",
      "sourceMap": true,
      "outDir": "dist"
    },
    "lib" : ["es2015"]
  }

Upon running npm run start, an issue arises:

 Module '"/mnt/c/Users/raffa/Desktop/simple_app/node_modules/@types/express/index"' can only be default-imported using the 'esModuleInterop' flag

2 import express from 'express';
         ~~~~~~~

  node_modules/@types/express/index.d.ts:133:1
    133 export = e;
        ~~~~~~~~~~~
    This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag.

What could be the solution to this problem?

Answer №1

Executing tsc with a specified file path via the command line will override the settings in your tsconfig.json

You can find further information on this topic in the Typescript documentation (https://www.typescriptlang.org/docs/handbook/tsconfig-json.html):

When providing input files directly through the command line, any tsconfig.json configurations are disregarded.

This means that the esModuleInterop section in your tsconfig.json won't take effect if you run tsc index.ts.

A workaround is to use

import * as express from 'express';
, but be aware that other configuration issues may arise when ignoring TS configs.

An issue raised with using tsc -w && node index.js (as mentioned in a comment) is that the -w flag causes it to wait instead of terminating automatically, preventing execution of the code after "&&".
Consequently, the node index.js portion is never reached.
(Fortunately, this time, tsc does not target a specific file, hence the config is retained)

In addition, since your outDir is configured as dist, the compiled file will be placed there. Therefore, consider using the following alternative:

tsc && node ./dist/index.js

Answer №2

Encountering this error led me to simply restart VS Code

Interestingly, the error unexpectedly surfaced despite the fact that I had previously run the project successfully multiple times

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

Getting command line argument parameters in React can be achieved by utilizing the `process.argv`

Is there a way to retrieve command line argument parameters in React? I currently have a React codebase that is utilizing Webpack. When running the following commands - npm run build -- --configuration=dev or npm run build -- --configuration=qa I need t ...

Encountered an error while attempting to install the @typescript-eslint/eslint-plugin

After starting the installation process for eslint plugins, I encountered an issue with @typescript-eslint/eslint-plugin. The plugin requires installation using--legacy-peer-deps, but this approach may introduce potential bugs by accepting an incorrect an ...

Troubleshooting Angular 2: Why Array Interpolation is Failing

Greetings everyone, I am diving into Angular 2 and attempting to create a basic Todo application. Unfortunately, I've hit a roadblock. My array interpolation seems to be malfunctioning. Any assistance would be greatly appreciated. Here is my AppCompo ...

What strategies can I use to address the issue of requiring a type before it has been defined?

Encountered an intriguing challenge. Here are the types I'm working with: export interface QuestionPrimative { question : string; id : string; name : string; formctrl? : string; formgrp? : string; lowEx ...

The current issue I am facing is that the option disabled with value="null" selected is not being shown on the screen. Instead, it should display as "Choose User Types"

https://i.sstatic.net/JqZ7O.png <select class="form-control" id="ddSelectaTopic" onchange="if(this.value==='') {this.style.color='#999'} else {this.style.color='#333'}" [(ngModel)]="us ...

Can I combine tuple types in Typescript?

type A1 = ['x','y','z'] type A2 = ['u','v','w'] type AN = [.., .., ..] type C = Combine<A1,A2,...,AN> //or Combine<[A1,A2,...,AN]> //resulting in ['x','y','z& ...

Where does the csrf value get generated and saved in hackathon-starter with Lusca?

As a newcomer to Node, I apologize if this question seems basic. I'm attempting to switch the project on github to use ejs views instead of what is currently there, but I am having trouble understanding how they are generating the csrf token. The see ...

Node.js is experiencing difficulties loading the localhost webpage without displaying any error messages

I am having trouble getting my localhost node.js server to load in any browser. There are no errors, just a buffering symbol on the screen. The code works fine in VS Code. Here is what I have: server.js code: const http = require("http"); const ...

Unable to utilize mobs decorator as an error is occurring: Experimental syntax 'decorators-legacy' is not enabled at the moment

Having successfully used mobx decorators in a React Native project, I now encounter an issue while developing a website with the React.Js library. The error message states: Support for the experimental syntax 'decorators-legacy' isn't curre ...

Creating personalized functions in Object.prototype using TypeScript

My current situation involves the following code snippet: Object.prototype.custom = function() { return this } Everything runs smoothly in JavaScript, however when I transfer it to TypeScript, an error surfaces: Property 'custom' does not ex ...

I find myself hindered by TypeScript when trying to specify the accurate constraints for getUserMedia

I'm having difficulty getting a screen to stream within my Angular 5 Electron application. I am utilizing the desktopCapturer feature provided by Electron. Below is an excerpt of my code: loadCurrentScreensource() { desktopCapturer.getSources({ ...

The object returned by bodyParser is not a string but a data structure

I have been working on implementing a JSON content listener in Typescript using Express and Body-parser. Everything is functioning perfectly, except when I receive the JSON webhook, it is logged as an object instead of a string. import express from 'e ...

The error message "Cannot access property 'installed' as it is undefined in Express.js" was displayed

Struggling to find a solution for this problem with Express.js and the Google Sheets API. My Express application is processing a POST request, passing it to a function that uses OAuth2 to append data as a new row in a Google Sheet. Upon calling updateShee ...

Import JSON data into Angular 2 Component

After much effort, I have finally figured out how to load JSON data into an Angular 2 Component. datoer.service.ts: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from ...

Executing npx command with organized packages

When attempting to execute a scoped package with npx, I am running into some issues. It seems like the only way to do it is by specifying the package directly, like so: npx -p @foo/bar bar This command will successfully download @foo/bar and execute the ...

Having trouble sending a POST request with body parameters in Node.js? The error "undefined req.body.param" might be popping up when you're

I've encountered an issue with my server.js code: const bodyParser = require('body-parser'); const cors = require('cors'); const morgan = require('morgan'); var express = require('express') , http = requir ...

Automatic Update Division in Jade Template (Node.js/Express)

In my development project using Node.js, Express, Jade, and Redis, I have successfully created an app that pulls telnet stream data from reversebeacon.net. This data is then cross-referenced with Redis databases containing amateur radio club member informa ...

Guide to developing a private shared Node.js module using TypeScript

I have a unique idea for a nodejs server service, consisting of: a REST API, and various asynchronous workers. My vision is to separate these components into different subnets and git repositories while still enabling them to access the same database en ...

Exploring the capabilities of the Express router and its various methods

I am curious about var server = http.createServer(function(req, res) { // something } server.listen(3000); Is the server created and listening on port 3000 immediately after running this code block, or is it only created at first and then started ...

Using an array as a query parameter in Swagger OpenApi 3.0

I have provided the following code to obtain an array of values as query parameters (in Node-express, nodejs v14.17 and OpenAPI version 3.0.1), - name: abcd description: abcd in: query required: false schema: ...