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