'React' refers to a UMD global, but the current file is a module

Viewed 98340

I updated my project to create react app 4.0, and I'm slowing moving over my files to TypeScript. I know with this new version you don't have to repetitively import React from 'react'. However, within all of my TS files where I'm not importing React I receive this error:

'React' refers to a UMD global, but the current file is a module. Consider adding an import instead.ts(2686)`

I know I can fix it by importing React, but I thought this was no longer needed. Also, could someone explain the meaning of this error?

My basic TSX file

const Users = () => {
    return <>Teachers aka Users</>;
};

export default Users;
6 Answers

Create React App supports the new JSX transformation out of the box in version 4 but if you are using a custom setup, the following is needed to remove the TypeScript error when writing jsx without import React from 'react':

  • typescript of at least version 4.1
  • react and react-dom of at least version 17
  • tsconfig.json must have a jsx compilerOption of react-jsx or react-jsxdev

example:

// tsconfig.json
{
  "compilerOptions": {
    ...
    "jsx": "react-jsx"
    ...
  },
}

TypeScript documentation for its support of React 17 JSX Factories can be found here

Adding

import React from 'react'

fixes this issue

What Dan wrote is correct you can change TS config.json:

// tsconfig.json
{
  "compilerOptions": {
    ...
    "jsx": "react-jsx"
    ...
  },
}

Or just import React inside the file Component that's giving you the error:

import React from 'react'

In my case, it was unrelated to any of this.

I was using Visual Studio Code, and I opened the folder not at the root which had tsconfig.json file, but at one level inside at src folder.

I was getting the error: Parsing error: Cannot read file :C\MyProject\tsconfig.json.eslint

Which indirectly caused 'React' refers to a UMD global, but the current file is a module

Reopening folder at project level resolved the issue. :\

I ran into this issue and finally realized that changing tsconfig.json doesn't work if you have ts-jest set up. Make sure if you have ts-jest set to:

module.exports = {
  ...
  globals: {
    ...
    "ts-jest": {
      ...
      tsconfig: {
        ...
        jsx: "react-jsx", // *** HERE ***
        ...
      },
    },
  },
  ...
};
Related