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

使用CDN引入React时TS编译报错TS2307:找不到'react'模块

解决React+TypeScript CDN加载下tsc编译报错问题

问题根源

  1. 模块配置不匹配:你的tsconfig.json中module和moduleResolution设为NodeNext,这是针对Node.js环境的模块解析逻辑,但代码运行在浏览器中,依赖全局变量而非Node.js模块系统。
  2. 类型定义识别异常:全局安装的@types/react和@types/react-dom不会被TypeScript自动检测,TypeScript默认优先读取本地项目node_modules中的类型定义。
  3. 冗余的import语句:CDN加载的React会挂载为全局window.React和window.ReactDOM变量,无需通过import引入模块。

解决方案

1. 调整TypeScript配置(tsconfig.json)

修改配置适配浏览器全局变量环境:

{
    "compilerOptions": {
        "target": "es2020",
        "module": "None", // 禁用模块系统,适配全局变量模式
        "moduleResolution": "Node",
        "strict": true,
        "noEmitOnError": true,
        "types": ["react", "react-dom"] // 指定加载全局类型定义
    },
    "include": ["**/*.ts"],
    "exclude": ["**/*.js"]
}

2. 修改test.ts移除冗余import

直接使用全局变量,删除模块导入语句:

const sHelloPrefix: string = "Hello,";

class HelloComponent extends React.Component {
    render() {
        return React.createElement("div", null, `${sHelloPrefix} ${this.props.toWhat}`);
    }
}

document.addEventListener("DOMContentLoaded", () => {
    const oReactRoot = ReactDOM.createRoot(document.getElementById("app"));
    oReactRoot.render(React.createElement(HelloComponent, {toWhat: "World! (from TS)"}));
});

3. 本地安装类型定义(推荐替代全局安装)

全局依赖易出现路径识别问题,建议本地初始化项目并安装依赖:

  • 进入项目目录:cd C:\inetpub\wwwroot\TypeScriptReactTest
  • 初始化npm项目:npm init -y
  • 安装本地依赖:npm install --save-dev typescript@5.5.2 @types/react@18.2 @types/react-dom@18.2

本地安装后,TypeScript会自动读取node_modules/@types中的类型定义,可省略tsconfig.json中的types字段。

4. 重新编译

执行tsc命令即可正常编译,生成的test.js可配合HTML中的CDN脚本在浏览器运行。


关于JSFiddle的差异

JSFiddle的TypeScript环境默认自动识别全局React变量,且隐式引入了React类型定义,无需手动配置模块系统,因此无需写import语句即可运行。

内容的提问来源于stack exchange,提问作者Jordan Rieger

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 12:44:56