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?
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.
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.
A simple solution is to set "esModuleInterop": true
in compilerOptions
of your tsconfig.json
file.
Example:
{
"compilerOptions": {
"esModuleInterop": true
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With