TypeScript中期望用import React from 'react'却只能用import * as React的问题
import * as React from "react" Instead of Default Import in TypeScript Hey there! I’ve run into this exact snag before, so let me break down what’s going on and how you can get the import React from "react" syntax working if that’s your preference.
The Root Cause
React’s npm package is historically structured as a CommonJS module (using module.exports = React instead of ES module-style default exports). By default, TypeScript treats CommonJS modules differently—it doesn’t automatically map their top-level exports to ES module default imports. That’s why import React from "react" throws an error: TypeScript doesn’t recognize a proper default export from the react package unless you tell it to handle CommonJS modules with interoperability in mind.
The Fix: Update Your tsconfig.json
You can make the default import work by enabling two key compiler options in your tsconfig.json:
esModuleInterop: true: This tells TypeScript to emulate ES module interoperability with CommonJS modules. It adds small helper functions that let you use default imports for packages that rely onmodule.exports.allowSyntheticDefaultImports: true: This allows TypeScript to generate "synthetic" default exports for modules that don’t have an explicit ES module default export (like React’s CommonJS build).
Here’s how your compilerOptions should look with these settings:
{ "compilerOptions": { "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "ES6", "module": "ESNext", // Keep your other existing configuration options here } }
After saving these changes, you’ll be able to use import React from "react" just like you want, and TypeScript will correctly resolve the react package from node_modules.
A Quick Note If You Can’t Modify tsconfig
If for some reason you can’t adjust your TypeScript config (e.g., working on a legacy project with strict constraints), import * as React from "react" is totally valid and will keep working perfectly. It’s just a different way to import the entire React namespace, which is fully supported in TypeScript.
内容的提问来源于stack exchange,提问作者White

