如何在 Create React App 中使用 TSX 文件
要在 Create React App 中支持 TSX,需要进行以下步骤:
- 安装 TypeScript 和相关的依赖
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
-
修改 src 目录下的 App.js 为 App.tsx,并修改其中的代码以适应 TypeScript 的语法。
-
修改 tsconfig.json 文件,使其支持 TSX 文件。
{
"compilerOptions": {
"jsx": "react",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"module": "esnext",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "./build",
"baseUrl": "."
},
"include": [
"src"
]
}
- 在 package.json 文件中添加以下代码,使其支持 TSX 文件。
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
],
"overrides": [
{
"files": ["**/*.tsx"],
"rules": {
"react/prop-types": "off"
}
}
]
},
- 重新启动 Create React App 应用程序。
npm start
现在,Create React App 应用程序已经支持 TSX 文件了。可以在 src 目录下创建任何 TSX 文件来编写 React 组件。
原文地址: http://www.cveoy.top/t/topic/kUsh 著作权归作者所有。请勿转载和采集!