Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; 
like image 960
Rafael Avatar asked Nov 03 '20 02:11

Rafael


People also ask

What is a UMD Global?

A UMD module is one that can either be used as module (through an import), or as a global (when run in an environment without a module loader). Many popular libraries, such as Moment.js, are written this way. For example, in Node.js or using RequireJS, you would write: import moment = require("moment");

Could not find a declaration file for module react JSX runtime?

When you have this error, it is usually because you installed a library and you didn't install the types of that library. To fix this error, you need to install @types/library-name using your package manager (npm or yarn).

How do I import ReactDOM into react?

import ReactDOM from 'react-dom'; or if you're using ES5 you can just do: var ReactDOM = require('react-dom'); and then you can use ReactDOM.


2 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 version 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

like image 95
Dan Barclay Avatar answered Oct 10 '22 01:10

Dan Barclay


This error message comes from TypeScript compiler. The React 17 new jsx transform is not currently supported in Typescript 4.0, and will be supported in 4.1.

TypeScript v4.1 Beta - React 17 JSX Factories

like image 27
Matt Peng Avatar answered Oct 10 '22 01:10

Matt Peng