You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中期望用import React from 'react'却只能用import * as React的问题

Why You Need 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 on module.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:57:32