使用create-react-app 搭建react + ts + antd框架


 一、創建項目

 使用npx create-react-app (項目名) --template typescript  創建項目

  ①如果App.tsx文件有如下報錯: (沒有報錯的請忽略)

 

 

 需要將tsconfig.json文件里的 "jsx": "react-jsx" 配置改為 "jsx": "react" 即可。

 

 

 

② 此時運行yarn start會報錯

 

 此時需要將react-scripts版本4.0.0降級為3.4.4  (參考: https://stackoverflow.com/questions/64593336/typeerror-cannot-assign-to-read-only-property-paths-of-object-for-compileropt

③ 如遇到報錯 : TypeScript 引入第三方包,報無法找到模塊錯誤  (參考: https://www.cnblogs.com/xym4869/p/13323483.html)

 

二、安裝ant-design 並配置自定義主題、按需加載(參考antd官網)、絕對路徑的引用

yarn add antd @craco/craco craco-less
yarn add @babel/plugin-proposal-decorators babel-plugin-import --dev

 

①修改 package.json 里的 scripts 屬性:

"scripts": { "start": "set PORT=3000 && craco start", "build": "set GENERATE_SOURCEMAP=false && craco build", "test": "craco test" },

 

② 在項目根目錄創建一個 craco.config.js 用於修改默認配置 (參考: https://blog.csdn.net/qq_39223195/article/details/106287522

const CracoLessPlugin = require('craco-less'); const path = require('path') const pathResolve = pathUrl => path.join(__dirname, pathUrl) module.exports = { webpack: { alias: { '@@': pathResolve('.'), '@': pathResolve('src'), '@common': pathResolve('src/common'), '@config': pathResolve('src/config'), '@components': pathResolve('src/components'), } }, babel: { plugins: [ ['import', { libraryName: 'antd', style: true }], ['@babel/plugin-proposal-decorators', { legacy: true }] ] }, plugins: [ { plugin: CracoLessPlugin, options: { lessLoaderOptions: { lessOptions: { modifyVars: { '@primary-color': 'red' }, javascriptEnabled: true, }, }, }, }, ], };

 

③在根目錄創建 paths.json 文件

{ "compilerOptions": { "baseUrl": "./", "paths": { "@@/*": ["./*"], "@/*": ["src/*"], "@common/*": ["src/common/*"], "@config/*": ["src/config/*"], "@components/*": ["src/components/*"] } } }

 

④修改tsconfig.json配置,添加上以下內容。將paths.json文件引入。直接在tsconfig.json文件里寫會報錯。 這樣配置完之后引入文件的時候可以@/xxx/xxx並且會有提示。

"extends": "./paths.json",

 

⑤ 將App.css和index.css改為App.less和index.less

⑥ demo

 

 

三、代碼規范(eslint)的配置 (參考: https://www.npmjs.com/package/eslint)

./node_modules/.bin/eslint --init

 

如果是windows系統需要將‘/’換成 ‘\’, 然后按照自己的需求來選擇配置即可。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM