Lyd*_*dia 10 javascript typescript reactjs
我在将TypeScript添加到现有的 create-react-app应用程序时遇到了困难.以前我总是在开始项目之前添加它,只是通过create-react-app my-app --scripts-version=react-scripts-ts,但现在不起作用.
我在这里找到的唯一"解决方案" 是:
react-scripts-tstsconfig.json,tsconfig.test.json
,tslint.json从临时项目src文件夹到项目的src文件夹中.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.js它App.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)
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 了。
从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)
您可以在这里阅读更多内容。
| 归档时间: |
|
| 查看次数: |
4901 次 |
| 最近记录: |