React + TS: How to configure react+ TS: How to configure Flexbile

React + Typescript builds projects and implements screen adaptation

The installation

// NPM install -g create-react-app // If it has been installed for a long time, it is recommended to uninstall NPM uninstall -g create-react-appCopy the code

New project

npx create-react-app my-app --template typescript
Copy the code

Flexible + REM implementation adaptation

1. Install the plug-in

npm i lib-flexible --save
Copy the code
npm i postcss-px2rem --save
Copy the code
1.1 configuration
1.1.1 Configuring Meta Tags
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
Copy the code
1.1.2 Importing the Flexible File

Introduce Lib-flexible in the project entry file index.tsx

import 'lib-flexible';
Copy the code

The react editor will report an error saying “React cannot find the declaration file for the module” lib-flexible “. Solution: Add declaration.d.ts to the SRC directory to declare the module

declare module 'lib-flexible';
Copy the code
1.1.3 Configuring the Flexible File

React does not expose the Webpack file. There are two ways to do this

  1. Hidden Wabpack files can be exposed by using the NPM run eject command, but this method is not reversible
  2. Overwrite the configuration file via the React-app-rewired plugin
npm install react-app-rewired customize-cra -s
Copy the code

Change the package.json file

"scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-app-rewired eject"
  },
Copy the code

Create a new config-override.js file in the root directory

const { override, addPostcssPlugins} = require('customize-cra'); Module. Exports = override(addPostcssPlugins([require(" postCSs-px2REm-exclude ")) ({remUnit: 75, // // exclude: /node_modules/ I // plugin does not need to be converted to rem})]),);Copy the code

Modify the flexible.js source file

function refreshRem(){ var width = docEl.getBoundingClientRect().width; If (width/DPR < 1980) {width = 1980 * DPR; } else if (width / dpr > 5760) { width = 5760 * dpr; } // Original item 3840, set to 48 equal parts. 1rem is equal to 80px var rem is equal to width / 48; docEl.style.fontSize = rem + 'px'; flexible.rem = win.rem = rem; }Copy the code

Modify the REM conversion configuration for Webpack to remUnit:80

1.1.4 Installing and Configuring less
npm install less less-loader -s
Copy the code

React + typescript configure aliases

1. Inconfig-overrides.jsIn the configuration

const { override, addWebpackAlias } = require('customize-cra');
const path = require("path");

module.exports = override(
  addWebpackAlias({
    '@' : path.resolve(__dirname, "./src"),
    '@components' : path.resolve(__dirname, "./src/components"),
    '@pages' : path.resolve(__dirname, "./src/pages"),
    '@utils' : path.resolve(__dirname, "./src/utils"),
    '@assets' : path.resolve(__dirname, "./src/assets"),
    '@app' : path.resolve(__dirname, "./src/app"),
  }),
);
Copy the code

2. To createtsconfig.extend.jsonfile

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "@api/*": ["src/api/*"],
      "@app/*": ["src/app/*"],
      "@assets/*": ["src/assets/*"],
      "@components/*": ["src/components/*"],
      "@utils/*": ["src/utils/*"]
    }
  }
}
Copy the code

Configuration of 3.tsconfig.json

{<! ----> Add extends option here "extends": "./ tsconfig.exten. json", "compilerOptions": {"target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx" }, "include": [ "src" ] }Copy the code

Webpack configuration principles

The override() method, which is a higher-order function, takes a variable number of arguments, each of which is a function signed const fn = (oldConfig) => newConfig; A new function, also signed by const fn = (oldConfig) => newConfig, is returned.

Override () internally calls the passed argument functions in turn, taking the newConfig returned by the former function as the oldConfig argument to the latter, resulting in the final Webpack Config.

function override(fns) { return function (oriConfig) { let finalConfig = oriConfig for (const fn of fns) { finalConfig =  fn(finalConfig) } return finalConfig } }Copy the code

See article: Get started with the Create React App and WebPack configuration customize-cra

React handles network requests — Axios

  1. Create and configure axiOS
import axios from "axios"; // set base address const devBaseUrl = "http://172.16.3.9:20101" Const publicIp = process.env.node_env === 'development'? devBaseUrl : devBaseUrl; // const divisionCode = '510000_2_0001'; const service = axios.create({ // baseURL: process.env.BASE_URL, baseURL: publicIp, timeout: 12000}) service. Defaults. Headers. Post [' the content-type '] = 'application/json / / request interceptor service.interceptors.request.use(config => { let divisionCode = localStorage.getItem('divisionCode'); config.params ={... config.params, ... {divisionCode}}; return config; }, error => Promise.reject(error)); / / response interceptor service. Interceptors. Response. Use ((response) = > {the if (the response. The status = = = 200) {/ / back to 200, Resolve (response.data)} else {// message.error(' response timed out ') return Reject (response.data.message)}}, (error) => {// message.error(' Request timeout, please refresh and retry ') return promise.reject (' Request timeout, please refresh and retry ') Please refresh again ')}) export default ServiceCopy the code
  1. Encapsulating network requests
import service from './request'; export const httpGet = (url: string, params? : any, config = {}) => { return new Promise((resolve, reject) => { service({ method: 'get', url, params, ... config }).then(response => { resolve(response); }).catch(error => { reject(error); }) }) } export const httpPost = ((url: string, data? : any, config = {}) => { return new Promise((resolve, reject) => { service({ method: 'post', url, data, ... config, }).then(response => { resolve(response); }).catch(error => { reject(error); })})})Copy the code