美文网首页
React项目搭建

React项目搭建

作者: 小姑凉喜欢无脸男 | 来源:发表于2022-10-20 16:43 被阅读0次

1、创建环境

环境 Node >= 14.0.0 和 npm >= 5.6 或 yarn

官方react创建项目方法
npx create-react-app my-app
cd my-app
npm start
使用yarn创建react项目

!!!错误方法

yarn create-react-app my-app 

正确方法

yarn create react-app my-app 

2、安装ant-design

根据ant官网安装依赖

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",
}

然后在项目根目录创建一个 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、多环境打包配置

参考文章三分钟教你搞定 React 项目多环境配置

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来指定环境

"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、状态管理

redux、react-redux配合使用

yarn add redux
yarn add react-redux

相关文章

网友评论

      本文标题:React项目搭建

      本文链接:https://www.haomeiwen.com/subject/inkjortx.html