使用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系統需要將‘/’換成 ‘\’,然後按照自己的需求來選擇配置即可。