Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve "can only be default-imported using the 'esModuleInterop' flag" in Visual Studio 2019?

Tags:

I'm upgrading my JavaScript files into TypeScript in Visual Studio 2019, to manage them better.

When I want to import a module from another file, I see squiggly lines complaining that:

x can only be default-imported using the 'esModuleInterop' flag

How should I solve this?

like image 312
mohammad rostami siahgeli Avatar asked Nov 06 '19 12:11

mohammad rostami siahgeli


People also ask

How do I fix the default can be imported using the esModuleInterop flag?

The error "Module can only be default-imported using esModuleInterop flag" occurs when we try to import a CommonJS module into an ES6 module. To solve the error, set the esModuleInterop option to true in your tsconfig. json file.

What is __ Importdefault?

The key is the __importDefault function. It assigns module ( exports ) to the default property for CommonJS modules: var __importDefault = (this && this. __importDefault) || function (mod) { return (mod && mod.


2 Answers

A simple solution is to set "esModuleInterop": true in compilerOptions of your tsconfig.json file.

Example:

{
  "compilerOptions": {    
    "esModuleInterop": true
  }
}
like image 70
lehoang Avatar answered Sep 18 '22 18:09

lehoang


I had this problem after adding a TypeScript JSX file (.tsx extension) using the Visual studio "add new item" feature, even though I did have esModuleInterop=true in my tsconfig. None of my other tsx modules gave this error and I found if I add a new text file and just rename it to .tsx the error doesn't occur.

After much hunting around, the culprit seems to be these lines which had been added to the csproj by visual studio

  <ItemGroup>
    <None Remove="ClientApp\src\public\foo.tsx" />
  </ItemGroup>

  <ItemGroup>
    <TypeScriptCompile Include="ClientApp\src\public\foo.tsx" />
  </ItemGroup>

I deleted them from the csproj and the error went away

like image 24
Andy Avatar answered Sep 17 '22 18:09

Andy