在使用 carete-react-app 命令創建項目前,首先需要確保全局已經安裝了 create-react-app 。
全局安裝 create-react-app:
npm install -g create-react-app
使用 create-react-app 創建項目:
yarn create react-app my-app --template typescript
到目前為止我們已經使用 create-react-app 創建了項目,且執行 yarn start 可以運行項目,但是你要是想往項目里面添加 react-router-dom 的時候就會報錯,提示你沒有安裝 react-router-dom 對應的 ts ,然后我們執行以下代碼安裝對應的 ts :
npm i --save-dev @types/react-router-dom
當你安裝完成 @types/react-router-dom 后,你會發現 react 又報錯了(這特么什么👻)。
這個時候怎么辦呢?把 node_modules 文件夾全部刪除,重新執行 yarn install 安裝插件。你會發現所有的錯誤提示都沒有了,切代碼也能正常運行。
接下來,你可以把 app.tsx 里面的代碼刪除掉,使用 react-router 官方提供的一些用例代碼來代替。
相關站點:
create-react-app: https://create-react-app.dev/docs/getting-started
react-router: https://reactrouter.com/web/example/basic