react create-react-app v5 Build a project from scratch

Foreword:

I haven’t used create-react-app for a project for a long time. This time I decided to build one myself for an h5 project with only a few pages (ps:mmp I haven’t used it for a long time and encountered a lot of problems when building it).

I have used umi before. The backend management system project uses the antd-pro framework. In fact, antd-pro is an integrated framework based on umi. Various things are packaged inside, ready to use right out of the box.

My environment is as follows:
create-react-app v5

    "axios": "^1.5.0",
    "http-proxy-middleware": "^2.0.6",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router": "^6.16.0",
    "react-router-dom": "^6.16.0",
    "customize-cra": "^1.0.0",
    "react-app-rewired": "^2.2.1"

There are many problems with the v5 version. There are many problems, and the methods in some plug-ins are not suitable (there are many pitfalls, many time: 2023-09-27).
The pitfalls I mentioned were caused by using react-app-rewired and customize-cra to configure some things when I didn't want to expose the webpack configuration. It is not a problem with create-reacr-app itself.

So if you don't want this trouble, you can directly npm run eject and use traditional webpack configuration.
If you don’t want to rewrite webpack with third-party plug-ins, you can read my article: react create-react-app v5 built from scratch (using npm run eject)

Building process:

1. Create a project:
Install Node and npm: Node >= 14.0.0 and npm >= 5.6

npx install -g create-react-app

npx create-react-app my-app

Insert image description here
npx is not a typo - it's the package runner that comes with npm 5.2+.

react official website documentation

2. Configure various necessary things

Run npm start and see the picture below, which means the project has been created successfully!
Project operation success renderings

Configure routing:

1. Download react-router-dom

npm install react-router-dom

1. First npm react-router-dom
2. Write the following code in App.js:

import React from "react";
import {
    
     BrowserRouter, Routes, Route } from "react-router-dom";
import routes from './routes';
const App = () => {
    
    
  console.log(routes)
  return (
    <BrowserRouter>
      <Routes>
        {
    
    routes.map((route) => (
          <Route key={
    
    route.path} path={
    
    route.path} element={
    
    route.component} />
        ))}
        {
    
    /* <Route path="*" element={<Home />} />  */}
      </Routes>
    </BrowserRouter>
  );
};

export default App;

App.js code screenshot
3.Write in index.js:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
   </React.StrictMode> 
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

index.js code screenshot

4. Create a new routes.js file under src and write:

// 导入你的页面组件  
import Home from './pages'; 
const routes = [
  {
    
     path: "/", component: <Home/>}
];

export default routes;

routes.js code screenshot
If you run and see the things in the Home component, it means success. After that, you can import other components in scr/router.js and just write the path and routers.

Note: react-router-dom v6 and v5 api are not the same. For example, in v5, Route is component and v6 is element. For specific writing methods, it is recommended to refer to the version documentation you are using!

If you encounter the Uncaught TypeError: Cannot read properties of null (reading 'useRef') error, you can see https://blog.csdn.net/weixin_44058725/article/details/133316898

Configure less:

You can refer to:
react create-react-app configuration less

Configure Proxy proxy:

Using http-proxy-middleware
1. Install http-proxy-middleware

npm install http-proxy-middleware --save

2. Create a new setupProxy.js in the root directory.
The code is roughly as follows:
Then when requesting the interface, use /api/xx and the proxy will be automatically used.

const {
    
     createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
    
    
    app.use(
      '/api',
      createProxyMiddleware({
    
    
        target: 'http://localhost:8000',
        changeOrigin: true,
        // pathRewrite: {  
        //     '^/api': '/',  
        //   },  
      })
    );
  };

Configure axios:

1. Install axios

cnpm install axios --save

2. Create a new request.js file in src/utils (if there is no utils, create a new directory and then create a request.js)
3. The request code is as follows:
This is the simplest configuration. You can configure the request interception according to your own needs. thing.

import axios from 'axios'

 // axios的配置文件, 可以在这里去区分开发环境和生产环境等全局一些配置
 const devBaseUrl = 'http://api.k780.com/'
 const proBaseUrl = 'http://xxxxx.com/'
 
 // process.env返回的是一个包含用户的环境信息,它可以去区分是开发环境还是生产环境
 export const BASE_URL =  process.env.NODE_ENV === 'development' ? devBaseUrl : proBaseUrl
 export const TIMEOUT = 5000

var request = axios.create({
    
    
    baseURL:BASE_URL,//基准地址
    timeout:TIMEOUT
})
//拦截请求
request.interceptors.request.use((config)=>{
    
    
    return config
})
//拦截响应
request.interceptors.response.use((response)=>{
    
    
    return response
},function (error){
    
    
    //对响应的错误做点什么
    return Promise.reject(error);
}
)
 
export default request;

Configure your own webpack without exposing eject:

  1. Download react-app-rewired and customize-cra-5
npm install react-app-rewired customize-cra-5 --save-dev

2. Create a config-overrides.js file in the project root directory

For example, when configuring less, it is recommended to refer to the configuration of less above:

const {
    
     override, addLessLoader, addPostcssPlugins } = require("customize-cra-5");

module.exports = override(
  addLessLoader({
    
      
    lessOptions:{
    
    
      javascriptEnabled: true,  
      modifyVars: {
    
     '@primary-color': '#1DA57A' }, // 你的主题色  
    },
  }) 
);

For example: load antd on demand (load on demand)

Note: antd-mobile does not need to be configured to manually load
antd-mobile on demand.
antd-mobile loads official website screenshots on demand
In fact, the higher version of antd also comes with on-demand loading and does not need to be configured (the code below is just a demonstration. If you have other UI libraries or plug-ins, you need to load them on demand. You can follow the steps below):
Insert image description here
antd official link is loaded on demand


Need to configure after cnpm install babel-plugin-import

const {
    
    
  override,
  addLessLoader,
  addPostcssPlugins,
  fixBabelImports,
} = require("customize-cra-5");

module.exports = override(
  // addPostcssPlugins([require("autoprefixer")]), //自动给样式加浏览器前缀 不过 cra自带了所以可以不用这个
  // addLessLoader({
    
    
  //   lessOptions:{
    
    
  //     javascriptEnabled: true,
  //     modifyVars: { '@primary-color': '#1DA57A' }, // 你的主题色
  //   },

  // })

  // 针对antd-mobile 实现按需打包:根据import来打包 (使用babel-plugin-import)
    fixBabelImports("import", {
    
    
    libraryName: "antd",
    libraryDirectory: "es",
    style: true, //自动打包相关的样式 默认为 style:'css'
  }),
);

For example: the path alias src is written as @/xxx

  const {
    
    
  override,
  addLessLoader,
  addPostcssPlugins,
  fixBabelImports,
  addWebpackAlias
} = require("customize-cra-5");
const path = require('path')
  addWebpackAlias({
    
    
    '@': path.resolve('src')
  }),

Then you can use @ to introduce files under src.

For example, introducing px2rem (although it is officially written this way, it does not work for me):

At present, I have found no solution in the issues (2023-09-28, maybe there will be in the future, because my project is urgent, I must use the px conversion to rem operation, in order to adapt to the mobile h5)
Insert image description here

  addPostcssPlugins([require("postcss-px2rem")({
    
     remUnit: 37.5 })])

Part of the content refers to the API of the React mobile terminal adaptation solution
customize-cra-5. You can check the documentation on github.
Screenshot of api part

customize-cra api doc

Guess you like

Origin blog.csdn.net/weixin_44058725/article/details/133314417