本人從Vue轉(zhuǎn)React知牌,首次搭建,遇坑無數(shù)斋配。特寫此文記錄茴迁,以供參考寄悯。
React官網(wǎng)簡介: https://react.docschina.org/docs/react-api.html
官方腳手架create-react-app:https://create-react-app.dev/docs/getting-started
typescript之tsconfig簡介:https://www.typescriptlang.org/docs/handbook/tsconfig-json.html
Ant Design of React:https://ant.design/docs/react/use-in-typescript-cn
1 使用腳手架 create-react-app初始化
// 安裝yarn,速度比較塊
npm install -g yarn
// 不建議安裝全局堕义,無法使用最新的腳手架
npm install -g create-react-app
// 卸載命令
npm uninstall -g create-react-app
// failed==>這個不行猜旬,總是報D://Program 路徑有空格的錯誤,查閱很多解決方案無法解決
yarn create react-app my-app
// ok==>不啟用--typescript
npm init react-app my-app
// ok==>啟用typescript模板倦卖。但是實際上并沒有自動添加洒擦,仍需要手動添加
npx create-react-app my-app3 --typescript
// 啟動程序,和npm run start是一樣的
yarn start
啟動后怕膛,頁面是白的熟嫩。F12顯示下圖錯誤:Uncaught TypeError: Cannot read property 'forEach' of undefined react-refresh-runtime問題,是由于之前瀏覽器安裝了react插件褐捻。
這挺可怕的掸茅,一個插件版本不一樣椅邓,導(dǎo)致頁面都看不了。
禁用React這個瀏覽器開發(fā)插件昧狮, 重新啟動后景馁,看到下面這個圖就表示運行ok了。
2 手動支持typescript
明明選擇的 --typescipt逗鸣,但是并未如期引入合住,只能手動引入了。參考:https://create-react-app.dev/docs/adding-typescript/
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
# or
yarn add typescript @types/node @types/react @types/react-dom @types/jest
安裝完成后撒璧, 手動將 App.js和index.js重命名為 App.tsx和 index.tsx
執(zhí)行yarn start后會自動添加 tsconfig.json 文件
yarn start
又遇到了下圖錯誤透葛,無法使用 JSX, 除非提供了 "--jsx" 標(biāo)志。
解決方法卿樱,點擊右下角的typescript版本4.0.3僚害,再點擊選擇TypeScript 版本4.0.3
選擇與之匹配的工作區(qū)版本4.1.2
終于不紅了。
3. 添加antd控件
https://ant.design/docs/react/use-in-typescript-cn
yarn add antd
修改 src/App.tsx殿如,引入 antd 的按鈕組件贡珊。
import React, { FC } from 'react';
import { Button } from 'antd';
import './App.css';
const App: FC = () => (
<div className="App">
<Button type="primary">Button</Button>
</div>);
export default App;
修改 src/App.css最爬,在文件頂部引入 antd 的樣式涉馁。
@import '~antd/dist/antd.css';
大功告成!
BUG參考解決方案:
https://www.cnblogs.com/chenxizhang/p/14035749.html
https://blog.csdn.net/sjk2054949/article/details/109298959