Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get rid of my "@types/react/index" can only be default-imported using 'esModuleInterp' flag lint in React/TypeScript

It's as simple as stated above: React 16.9.22 with TypeScript 3.8.2. It doesn't affect anything, just crowds my warning window form actually useful things.

In my tsconfig I have:

{
  "compilerOptions": {    
    "esModuleInterop": true
  }
}

But every file have the line import React from 'react';

I get the linting error:

.../node_modules/@types/react/index"' can only be default-imported using the 'esModuleInterop' flag

possibly relevant deps:

  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^2.22.0",
    "@typescript-eslint/parser": "^2.22.0",
    "cross-env": "^5.2.0",
    "eslint": "^6.6.0",
    "eslint-config-react-app": "^4.0.1",
    "eslint-plugin-flowtype": "^2.0.0",
    "eslint-plugin-import": "^2.14.0",
    "eslint-plugin-jsx-a11y": "^6.2.1",
    "eslint-plugin-react": "^7.18.3",
    "typescript": "^3.8.2"
  },
like image 242
naspinski Avatar asked Mar 05 '20 17:03

naspinski


3 Answers

What worked for me was adding the following in my tsconfig.json file in the compilerOptions:

"allowSyntheticDefaultImports": true,
"esModuleInterop": true
like image 86
George Avatar answered Nov 18 '22 03:11

George


import * as React from "react";
import * as ReactDOM from "react-dom";

This is the most futureproof way to import React. If you set --allowSyntheticDefaultImports (or add "allowSyntheticDefaultImports": true) in your tsconfig.json you can use more familiar imports:

import React from "react";
import ReactDOM from "react-dom";

source: https://github.com/typescript-cheatsheets/react

like image 3
HiLuLiT Avatar answered Nov 18 '22 02:11

HiLuLiT


Alternatively, we can separate the imports as below for example

import React, { useState, useEffect, FC } from 'react';

to

import * as React from 'react';
import { useState, useEffect, FC } from 'react';
like image 2
Bhuwan Maharjan Avatar answered Nov 18 '22 02:11

Bhuwan Maharjan