This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.

preface

If you use React, or want to learn React, and are still struggling with the configuration of create-React-app, this article may help you

If it helps you, please don’t begrudge your Star~

  • Cache-alive is used in VUE and React is used in Reactreact-keeperCan solve this problem perfectly, and use more convenient and simple
  • Ant Mobile has been upgraded from V2 to V5, and it’s time for an update
  • If you don’t understand DVA, you can read the detailed usage document on The Language Sparrow. From the most intuitive point of view,dvaCompared to thereduxMore concise, more convenient to use

🎉 React mobile development scaffolding, technical stack React (hook) + ANTd moblie + typescript + react-Keeper + DVA

The scaffolding is created based on the Create React app to quickly build React mobile projects

gitHub: react-mobile

Online address: React-mobile-domesy

React Mobile primer

In addition, for those who are just interested in PC, I recommend a round of Ant Design Pro V5

Basic configuration

So let’s create a project using NPX, NPX create-react-app react-mobile

React-mobile (esLint compatible)

To create ts, just modify the command (ts).

NPX create-react-app react-mobile --template typescript

1. Create a project configuration file

The plug-in

react-app-rewired customize-cra

Execute the command

npm install react-app-rewired customize-cra --save

Function:

Without eject, override the create-react-app configuration to form config-overrides

Configuration:

React-scripts under script in package.json can be replaced with react-app-rewired

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

The config-overrides. Js file is then created in a further directory, and all subsequent configurations are in this file

const { override } = require('customize-cra');

module.exports = override(

);
Copy the code

2. Configure the LESS file

The plug-in

less less-loader

Execute command:

yarn add less less-loader -D

Function:

Support for Less filesCopy the code

Configuration: in the config-overrides. Js file

const { addLessLoader } = require('customize-cra'); module.exports = override( ... , addLessLoader({lessOptions: {javascriptEnabled: true, modifyVars: {// Global common style, you can use this file to make a configuration file '@primary-color': '#1DA57A'}, localIdentName: '[local]--[hash:base64:5]' // Customize CSS Modules localIdentName}}),...) ;Copy the code

3. Compress JS and CSS

The plug-in

compression-webpack-plugin

Execute the command

yarn add compression-webpack-plugin -D

Function:

Compressing JS and CSS

Configure in config-overrides. Js file

Note: For better configuration, we will be divided into development mode and packaging mode, we only need to configure the corresponding packaging mode, in addition, the default algorithm for gzip if there are changes can be changed

const CompressionWebpackPlugin = require('compression-webpack-plugin'); Const addCustomize = () => config => {// Package mode if(process.env.node_env === 'production') {config.devtool = false; Plugins = [...config.plugins, new CompressionWebpackPlugin({test: /. Js $|. CSS $/, / / compression js and CSS threshold: 1024, // Only resources larger than this value are processed, } else if(process.env.node_env === 'development'){} return config} module.exports = override(... , addCustomize() );Copy the code

4. Configure unique gadgets

As a programmer, we can add a little bit of something to a project, like a specific logo, so let’s add a little bit of something unique to the project

Combine node.js with let’s add DOMESY to this project when packaged 😄

The plug-in

The clear: clear screen

Chalk: Decorative, adding color to the output on the terminal

Figlet: The function is to convert letters into pictures to make them more eye-catching

Using the command

Yarn add figlet clear chalk@^ 4.1.0-s

Configure it in addCustomize

Const addCustomize = () => config => {// Customize if(process.env.node_env === 'production') {... const { promisify } = require('util'); const clear = require('clear') const chalk = require('chalk') const figlet = promisify(require('figlet')) clear() const log = content => console.log(chalk.blue(content)) figlet('DOMESY ! ').then(res => log(res)) ... } else if(process.env.NODE_ENV === 'development'){ } return config }Copy the code

Note here the version with chalk as ‘^4.1.0’

Let’s take a look at the effect

5. Install the component library

The component library we have chosen here is Ant-Desgin-Mobile, which has just been updated from V2 to V5, so all the components of the base V2 are not available

The plug-in

antd-mobile

Execute the command

yarn add antd-mobile@next

And then you can just import it

import { Button } from 'antd-mobile'

retrun (
  <Button color='primary'>Primary</Button>
)
Copy the code

6. Unit conversion

As you all know, on the PC side, CSS is based on PX, and on the mobile side, REM is based on REM. If you do mobile side, it will be very troublesome to convert PX to REM, which requires a plug-in to automatically convert it

Must work in less files, inline styles are useless

Plug-in postcss px2rem – exclude lib – flexible

Function: Automatically convert PX to REM

Execute command:

yarn add postcss-px2rem-exclude lib-flexible -S

Configure the lib – flexible

We just need to introduce import ‘lib-flexible in index.js

Configuration postcss px2rem — exclude

For convenience, we can just configure in package mode, so that the units in development mode remain PX

module.exports = override( ... , process.env.NODE_ENV === 'production' ? AddPostcssPlugins ([require(" postCSs-px2REm-exclude "))({remUnit: 37.5, exclude: /node_modules/ I})]) : null, addDecoratorsLegacy(), ... ) ;Copy the code

Note:

  • For easy debugging, use only in package mode, not development mode
  • The page needs to be configured. Usually, the H5 standard is 375

7. Remove esLint warnings

Remove esLint, “eslintConfig” configuration rule in package.json

{  
  ...,
	"eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ],
    "rules": {
      "no-undef": "off",
      "no-restricted-globals": "off",
      "no-unused-vars": "off"
    }
  },
  ...
}
Copy the code

Also, we can introduce disableEsLint

const { disableEsLint } = require('customize-cra'); module.exports = override( ... DisableEsLint (), // Ignore esLint warnings);Copy the code

8. Configure the alias

Just import addWebpackAlias in customize-cra

const { override, addWebpackAlias } = require('customize-cra'); module.exports = override( ... , addWebpackAlias({ ["@/"]: path.resolve(__dirname, "src/") }), ... ) ;Copy the code

If it is TS, the alias is still not recognized in the file and needs to be configured in tsconfig.json

Json {"extends": './paths.json',... {in} in the path. The json "compilerOptions" : {" baseUrl ":" SRC ", "paths" : {" @ / * ": [' * ']}}}Copy the code

So you don’t get an error

9. Pack in modules

It is divided into development environment and generation environment in built-in, corresponding to production and development mode respectively

Of course these are under process.env

In development we have a variety of environments, usually companies have at least a test environment and a formal environment, in a better gray environment

Each environment corresponds to the interface domain name is different, but we correspond to the package

In fact, there are many ways, the lowest set a variable manually switch, on top of the monitoring address bar for packaging (this is very limited, address change code needs to change ~, also relatively low)

So is there a better way? We want to use the name command to type the package corresponding to the environment, so that it is very convenient to return

Plug-in: cross – env

Execute the command

yarn add cross-env

Configuration: in package.json

{
	...,
  "scripts": {
    "start": "react-app-rewired start ",
    "start:pre": "cross-env REACT_APP_ENV=pre react-app-rewired start",
    "build": "react-app-rewired build",
    "starbuildt:pre": "cross-env REACT_APP_ENV=pre react-app-rewired start ",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
  },
  ...
}
Copy the code

That’s ok

All you need to do is run YARN Run start:pre

REACT_APP_ENV = pre, we can use this variable as a standard for judging, module packaging

Let’s print process.env

10. Configure decorators

Decorators can only be used with class components. Hook decorators can only be used with class components. Hook decorators can only be used with class components

Plug-in: @ Babel/plugin – proposal – decorators

Run the yarn add @babel/plugin-proposal-decorators command

const { override, addDecoratorsLegacy } = require('customize-cra'); module.exports = override( ... , addDecoratorsLegacy(), ... ) ;Copy the code

11. Configure packaging analysis

We can analyze the package size based on the written pages

Plug-in: webpack – bundle – analyzer

Execute the command

yarn add webpack-bundle-analyzer

Instead of starting a Web service, the package generates a static report file report.html under build

const { override, addWebpackPlugin } = require('customize-cra'); const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer') module.exports = override( ... , process.env.NODE_ENV === 'production' ? addWebpackPlugin( new BundleAnalyzerPlugin({ analyzerMode: 'static' ) : undefined );Copy the code

12. Other matters

  • In package.json, you need to configure “.” in homepage
{
  ...,
  "homepage": ".",
	...
}
Copy the code
  • Change the index.html in public to
<meta name="viewport" content="width=device-width, initial-scale=1, The shrink - to - fit = no, minimum - scale = 1.0, the maximum - scale = 1.0, user - scalable = no "/ >Copy the code

This article is for reference only, if there is any wrong place, welcome to leave your valuable opinion in the comments section