将TypeScript添加到现有的create-react-app应用程序

Lyd*_*dia 10 javascript typescript reactjs

我在将TypeScript添加到现有的 create-react-app应用程序时遇到了困难.以前我总是在开始项目之前添加它,只是通过create-react-app my-app --scripts-version=react-scripts-ts,但现在不起作用.

我在这里找到的唯一"解决方案" 是:

  1. 用.创建一个临时项目 react-scripts-ts
  2. 复制tsconfig.json,tsconfig.test.json ,tslint.json从临时项目src文件夹到项目的src文件夹中.
  3. package.json,更改脚本部分中对react-scriptsto的所有引用react-scripts-ts.

这似乎是一个奇怪的解决方法,而且效率不高.有谁知道是否可以以比这更好的方式添加它?

Mei*_*ari 24

您可以使用以下命令之一将打字稿添加到现有项目:

要将 TypeScript 添加到现有的 Create React App 项目,请首先安装它:

npm install --save typescript @types/node @types/react @types/react-dom @types/jest
Run Code Online (Sandbox Code Playgroud)

或者

yarn add typescript @types/node @types/react @types/react-dom @types/jest
Run Code Online (Sandbox Code Playgroud)

你可以在这里阅读更多

但问题是,当您更改除 index.js 之外的文件时,App.jsApp.tsx 会给您一个错误 module not find error can't parse './App' 。此问题的根源是缺少 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"
  ]
}
Run Code Online (Sandbox Code Playgroud)

  • 你不使用--save。但是--save-dev (2认同)

Joe*_*oee 22

如果要将 TypeScript 添加到现有的 React 应用程序中,请使用以下命令

npm install --save typescript @types/node @types/react @types/react-dom @types/jest
Run Code Online (Sandbox Code Playgroud)

将文件重命名为 .ts 或 .tsx,例如将 index.js 重命名为 index.ts 或 index.tsx,然后启动服务器。这将自动生成 tsconfig.json 文件,您就可以在 TypeScript 中编写 React 了。

  • 如果我重命名“index.js”,不会发生错误,但如果我对其他文件执行此操作,此错误会显示“找不到模块:错误:无法解析...”。也没有生成`tsconfig.json`文件 (12认同)
  • @UMR您需要手动初始化打字稿`npx tsc --init`并在tsconfig.json中设置`"jsx": "react"` (6认同)

use*_*640 5

从react-scripts 2.10开始,您可以将TypeScript添加到现有项目中或在创建新项目时。

现有项目

yarn add typescript @types/node @types/react @types/react-dom @types/jest
Run Code Online (Sandbox Code Playgroud)

...然后将.js文件重命名为.tsx

新项目

yarn create react-app my-app --typescript
Run Code Online (Sandbox Code Playgroud)

您可以在这里阅读更多内容。

  • 它不起作用,`找不到模块:错误:无法解析`出现 (9认同)
  • tsconfig 文件呢?我们不需要添加这个吗? (2认同)