您可以使用以下命令之一将TypeScript添加到现有项目中:
要将TypeScript添加到现有的Create React App项目中,请先安装它:
npm install
或者
yarn add typescript @types/node @types/react @types/react-dom @types/jest
你可以在这里阅读更多信息
但问题是,当你改变除了index.js之外的文件,例如将App.js
更改为App.tsx
时,它会出现模块未找到错误,无法解析 './App'。这个问题的根源是缺少一个tsconfig.json文件。因此通过创建一个tsconfig.json文件,就可以消除这个错误。我建议使用以下tsconfig:
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"],
"exclude": [
"node_modules"
]
}
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
在安装完成后,将任何.js
文件重命名为.tsx
并开始使用 TypeScript。请注意,在 TypeScript 中编写 React 组件时,需要为组件及其 props 定义类型。在下面的示例中,我们定义了一个HelloProps
类型,并在Hello
组件中使用它:import React from 'react'; type HelloProps = { name: string; }; function Hello({ name }: HelloProps) { returnHello, {name}! ;
}
export default Hello;
TypeScript 也可以帮助捕获其他类型错误,例如使用未定义的变量或访问不存在的属性,这些都可能会导致应用程序崩溃。因此,使用 TypeScript 可以使您的代码更加健壮和可维护。 - Blundering Philosopher