使用 create-react-app 创建的 React 应用默认使用 JavaScript 作为主要语言,但是也可以使用 TypeScript 来编写代码。要使用 TypeScript,需要进行以下步骤:

  1. 安装 TypeScript

在终端中运行以下命令:

npm install --save-dev typescript
  1. 创建 TypeScript 文件

在 src 目录中创建一个名为 index.tsx 的文件。这是一个 React 组件的示例。

  1. 修改文件扩展名

将文件扩展名从 .js 改为 .tsx。

  1. 修改 package.json

在 package.json 文件中找到 'scripts' 对象,并将 'start' 和 'build' 命令中的 .js 改为 .tsx,如下所示:

"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject"
},
  1. 启动应用

在终端中运行以下命令启动应用:

npm start

现在,您可以使用 TypeScript 编写 React 组件了。

使用 create-react-app 创建 TypeScript React 应用

原文地址: http://www.cveoy.top/t/topic/kUsq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录