【发布时间】:2021-01-27 21:58:45
【问题描述】:
我在 VSCode 中使用开箱即用的 create-react-app my-app --template typescript 项目时遇到问题,无法识别任何元素。我经常收到错误 cannot find name xxx 'xxx' 是我在 JSX 中使用的任何 HTML 元素。
有趣的是,该项目最初将在零编辑的情况下运行。一旦我真正进入 App.tsx 并更改任何内容或创建一个非常基本的新组件,它就会中断。
这是我尝试按照 TypeScript Handbook Github 中的 this 教程制作的一个非常基本的组件。
// src/components/Hello.tsx
import React from 'react';
export const Hello = () => {
return <h1>Hello < /h1>;
};
再一次,这个项目是使用create-react-app my-app --template typescript 直接从推荐的 TypeScript 模板创建的。没有文件被编辑。
它带有他们自己的tsconfig.json 准备好了。
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": [
"src"
]
}
当然他们也有自己的package.json。
{
"name": "ts-trial",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"@types/jest": "^24.0.0",
"@types/node": "^12.0.0",
"@types/react": "^16.9.52",
"@types/react-dom": "^16.9.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.3",
"typescript": "4.0.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
再次没有文件被编辑 - 我运行命令 cded 到我的新项目中,创建 Hello.tsx 并且在我将元素放入 return 语句时它说 找不到名称'h1'。 ts(2304).
然后我去了App.tsx,一打开它,同样的错误也显示出来了。
我在 GitHub 上提交了一个问题,因为我不知道我是如何诚实地得到这个错误的。我已经搜索了几个小时,发现的大多数解决方案与我的特定问题无关。大多数解决方案都忘记将 React 的文件扩展名从 .js 或 .ts 更改为 .tsx。或者他们必须在package.json 中指定"@types/node": "^12.0.0",或在tsconfig.json 中指定target、lib、module 或include,所有这些我都有。
环境信息:
系统:
- 操作系统:macOS 10.15.6
- CPU:(4) x64 Intel(R) Core(TM) i7-7660U CPU @ 2.50GHz
二进制文件:
- 节点:14.6.0 - /usr/local/bin/node
- 纱线:1.22.4 - /usr/local/bin/yarn
- npm: 6.14.7 - /usr/local/bin/npm
浏览器:
- Firefox 开发者版 82.0b7(64 位)
npmPackages:
- 反应:^16.13.1 => 16.13.1
- 反应域:^16.13.1 => 16.13.1
- 反应脚本:3.4.3 => 3.4.3
npmGlobalPackages:
- 创建反应应用程序:3.4.1
代码编辑器:VSCode
【问题讨论】:
-
你能做一个Github repo,把整个项目(除了node_modules,为了节省空间)都提交给它吗?将其作为文件夹进行调试会容易得多,我们可以在其中看到您的组织,而不是在此处复制粘贴。
标签: reactjs typescript create-react-app