Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React + TypeScript: 'React' refers to a UMD global but the current file is a module. Consider adding an import instead. (Justification)

We are using React and TypeScript in our current project and I come across below behavior.

import React, { Component } from 'react';

I replace the above line with the one below since it seems to be using Component import only.

import { Component } from 'react';

And I was thrown below error

Error: 'React' refers to a UMD global but the current file is a module. Consider adding an import instead.

I tried looking it up on Stack and GitHub, found few articles and discussion but still unclear about why it's happening.

Would be more interested in whether React or Typescript is throwing it and WHY ? Not the ways to fix it.

Also some light around UMD, why it's used here ?

like image 520
Jaspreet Singh Avatar asked Feb 19 '19 16:02

Jaspreet Singh


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");

Do I need to import react in every component?

You no longer need to import React from "react" . Starting from the release 17 of React, JSX is automatically transformed without using React. createElement . However, other exports like hooks must be imported.

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

To solve the error "Cannot find module 'react/jsx-runtime' or its corresponding type declarations", make sure to install the typings for react running the command npm install --save-dev @types/react@latest @types/react-dom@latest and restart your dev server.


2 Answers

Are you rendering any jsx in the file? If so, you do need to import React, since those jsx tags compile into calls to React.createElement(). Without the import, the references to React are trying to reference a global variable, which then results in that error.

If you're using eslint, i'd recommend using eslint-plugin-react and turning on the rule react-in-jsx-scope, which will catch this case.

like image 61
Nicholas Tower Avatar answered Sep 27 '22 22:09

Nicholas Tower


The way JSX syntax is transpiled depends on compiler options, jsxFactory option defaults to React.createComponent. This means that <p/> is transpiled to React.createComponent('p'), and React is expected to exist in the scope of a module.

If there's no React import, it's expected that React global should exist.

like image 28
Estus Flask Avatar answered Sep 27 '22 21:09

Estus Flask