— React.js, TypeScript, Web Development — 1 min read
In modern React development, especially with the introduction of React 17, it's common to use JSX without explicitly importing React in every file. However, this can lead to a TypeScript error that confuses many developers. This article will guide you through resolving the TypeScript error "React refers to a UMD global, but the current file is a module."
The error occurs when using JSX in TypeScript files without importing React. This happens because TypeScript needs to know how to interpret the JSX syntax. From React 17, React introduced a new JSX transform that does not require importing React into every file, but this needs to be configured correctly in TypeScript.
To solve this issue, ensure you have:
Update your tsconfig.json
file to support the new JSX transform. Set the jsx
compiler option to react-jsx
for development and production builds or react-jsxdev
for development builds.
tsconfig.json
:1{2 "compilerOptions": {3 ...4 "jsx": "react-jsx",5 ...6 }7}
With this configuration, TypeScript will understand the new JSX transform, and you won't need to import React in files using JSX.
If you're working with Next.js, be aware that Next.js might overwrite the jsx
option. In this case, follow the Next.js specific documentation to ensure compatibility.
By configuring TypeScript correctly for the new JSX transform, you can enjoy the streamlined developer experience of not having to import React in every file using JSX. This makes your React code cleaner and more enjoyable to write.
Remember to keep your React and TypeScript versions up to date to take advantage of the latest features and improvements.