React項目搭建

1、創(chuàng)建環(huán)境

環(huán)境 Node >= 14.0.0 和 npm >= 5.6 或 yarn

官方react創(chuàng)建項目方法
npx create-react-app my-app
cd my-app
npm start
使用yarn創(chuàng)建react項目

?。?!錯誤方法

yarn create-react-app my-app 

正確方法

yarn create react-app my-app 

2、安裝ant-design

根據(jù)ant官網(wǎng)安裝依賴

yarn add antd

配置按需加載

$ yarn add react-app-rewired customize-cra
/* package.json */
"scripts": {
-   "start": "react-scripts start",
+   "start": "react-app-rewired start",
-   "build": "react-scripts build",
+   "build": "react-app-rewired build",
-   "test": "react-scripts test",
+   "test": "react-app-rewired test",
}

然后在項目根目錄創(chuàng)建一個 config-overrides.js 用于修改默認配置。

module.exports = function override(config, env) {
  // do stuff with the webpack config...
  return config;
};

安裝babel-plugin-import

$ yarn add babel-plugin-import
+ const { override, fixBabelImports } = require('customize-cra');

- module.exports = function override(config, env) {
-   // do stuff with the webpack config...
-   return config;
- };
+ module.exports = override(
+   fixBabelImports('import', {
+     libraryName: 'antd',
+     libraryDirectory: 'es',
+     style: 'css',
+   }),
+ );

3、多環(huán)境打包配置

參考文章三分鐘教你搞定 React 項目多環(huán)境配置

yarn add dotenv-cli -D

根目錄新建兩個文件


新建文件.png
?。?!一定是REACT_XXXX,就像vue項目VUE_XXXX
# .env.development
NODE_ENV=development
REACT_APP_BASE_API='http://xxxxxxx'
# env.production
NODE_ENV=production
REACT_APP_BASE_API='https://xxxxxxxx'

修改 package.json 中的 scripts來指定環(huán)境

"scripts": {
    "start": "react-app-rewired start",
    "build:dev": "dotenv -e .env.development react-app-rewired build",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-app-rewired eject"
  }

可以在 config-overrides.js打印出當前打包的BASE_URL


控制臺打印.png

4、路由

yarn add react-router-dom

5、狀態(tài)管理

redux、react-redux配合使用

yarn add redux
yarn add react-redux
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容