• React报错之Cannot find namespace context


    正文从这开始~

    总览

    在React中,为了解决"Cannot find namespace context"错误,在你使用JSX的文件中使用.tsx扩展名,在你的tsconfig.json文件中把jsx设置为react-jsx,并确保为你的应用程序安装所有必要的@types包。

    cannot-find-namespace-context.png

    这里有个例子来展示错误是如何发生的。

    // App.ts
    import React from 'react';
    
    interface UserCtx {
      first: string;
      last: string;
      age: number;
    }
    
    const AuthContext = React.createContext<UserCtx | null>(null);
    
    const authContext: UserCtx = {
      first: 'James',
      last: 'Doe',
      age: 30,
    };
    
    const App = () => {
      // ⛔️ Cannot find namespace 'AuthContext'.ts(2503)
      return (
        <AuthContext.Provider value={authContext}>
          <h2>Your app hereh2>
        AuthContext.Provider>
      );
    };
    
    export default App;
    

    上述代码片段的问题在于,文件的扩展名为.ts ,但是我们在里面编写JSX代码。

    tsx

    这是不被允许的,因为为了能在TypeScript文件中使用JSX,我们必须这样做:

    1. .tsx扩展名命名文件
    2. tsconfig.json文件中开启jsx选项

    确保所有你编写JSX代码的文件都有.tsx扩展名。

    // App.tsx
    import React from 'react';
    
    interface UserCtx {
      first: string;
      last: string;
      age: number;
    }
    
    const AuthContext = React.createContext<UserCtx | null>(null);
    
    const authContext: UserCtx = {
      first: 'James',
      last: 'Doe',
      age: 30,
    };
    
    const App = () => {
      return (
        <AuthContext.Provider value={authContext}>
          <h2>Your app hereh2>
        AuthContext.Provider>
      );
    };
    
    export default App;
    

    更新完文件的扩展名为.tsx后,如果问题仍未解决,请尝试重启你的IDE和开发服务器。

    打开tsconfig.json文件,并确保jsx选项被设置为react-jsx

    // tsconfig.json
    {
      "compilerOptions": {
        "jsx": "react-jsx", // 👈️ make sure you have this
        "target": "es6",
        "lib": ["dom", "dom.iterable", "esnext"],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "noFallthroughCasesInSwitch": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true
      },
      "include": ["src/**/*"]
    }
    

    jsx选项被设置为react-jsx时,它会导致编译器抛出.js文件,其中的JSX被改为_jsx调用。

    如有必要请重启你的IDE和开发服务器。你的开发服务器不会接收这些变化,直到你停止它并重新运行npm start命令。

    安装@types/包

    在React中出现"Cannot find namespace context"错误的另一个原因是,我们没有安装必要的@types/包。

    在项目的根路径下打开终端,并运行以下命令:

    # 👇️ with NPM
    npm install --save-dev @types/react @types/react-dom @types/node @types/jest typescript
    
    # ------------------------------------------------------
    
    # 👇️ with YARN
    yarn add @types/react @types/react-dom @types/node @types/jest typescript --dev
    

    该命令为reactreact-domnodejest安装类型声明文件,并安装typescript包。

    如果仍然报错,尝试删除node_modulespackage-lock.json文件(不是package.json),重新运行npm install并重启你的IDE。

    # 👇️ delete node_modules and package-lock.json
    rm -rf node_modules
    rm -f package-lock.json
    rm -f yarn.lock
    
    # 👇️ clean npm cache
    npm cache clean --force
    
    npm install
    

    如果错误仍然存在,请确保重新启动你的IDE和开发服务器。VSCode经常出现故障,重启有时会解决一些问题。

    手动添加

    如果你仍然得到"Cannot find namespace Context"的错误,打开你的package.json文件,确保它在devDependencies对象中包含以下包。

    // package.json
    {
      // ... rest
      "devDependencies": {
        "@types/jest": "^27.4.1",
        "@types/node": "^17.0.24",
        "@types/react": "^18.0.5",
        "@types/react-dom": "^18.0.1",
        "typescript": "^4.6.3"
      }
    }
    

    你可以尝试手动添加上述依赖,并重新运行npm install

    npm install
    

    或者安装依赖包的最新版本:

    # 👇️ with NPM
    npm install --save-dev @types/react@latest @types/react-dom@latest @types/node@latest @types/jest@latest typescript@latest
    
    # ------------------------------------------------------
    
    # 👇️ with YARN
    yarn add @types/react@latest @types/react-dom@latest @types/node@latest @types/jest@latest typescript@latest --dev
    
  • 相关阅读:
    [nlp] 索引:正向索引&倒排索引
    MySQL的数据库引擎介绍
    【算法|贪心算法系列No.4】leetcode55. 跳跃游戏 & 45. 跳跃游戏 II
    NX二次开发-C++使用IDA Pro反编译dll,追踪查看里面使用的UFUN API函数(三部曲1)
    国内率先自主数字源表及IGBT测试系统亮相半导体分立器件年会
    大疆面试笔试一部分总结
    Ansible简介-安装
    【技术分享】Python爬虫脚本+XML解析实现自动保存某商城的商品图
    DP杂谈【持续更新中】
    Jest:JavaScript的单元测试利器
  • 原文地址:https://www.cnblogs.com/chuckQu/p/16586443.html