React project construction


Write it at the front

Every time you build a react project, you will configure a lot of things, and you will forget how to configure it after a long time. This record is made for the convenience of self memory and for the rapid development of other developers when building react applications.

This project is based oncreate-react-appScaffold configuration. It mainly configures some commonly used methods in project development, such as webpacksassreduxThermal loadingagentAnd the introduction of other tool libraries.

Initialize project

First of all, to create a react project with create react app, you can refer to…


npm install -g create-react-app

Create an application

create-react-app my-app
cd my-app

Note: my app refers to the name of the project. Users can customize the project name

At this time, you can enter it on the command line

npm startStart the project to see the project launch page.

React project construction

npm run build: project release.

So a simple react project is initialized.

However, all configurations are hidden by default. To customize the configuration, you need to run a command:npm run eject
At this time, you will be prompted that the command is irreversible. Do you want to continue? Enter y, and all configuration items will come out. Will generate aconfigFolder, at this time you can also do some customized configuration.

Project configuration

Compatible with IE

introduceelement-reactUI framework will report an errorReferenceerror: 'symbol' not defined

  • Solution:

Introduction in the projectbabel-polyfill, in app.js Import it in

Configure webpack

Some configuration based on webpack

Configure sass

Sass is not configured for scaffolds by default. If sass is used in the project, it needs to be configured separately

1. Installation dependencynpm install --save-d node-sass sass-loader
2. Modify development environment and the release environment are separate configurations.

Modify cssloader
taketest: /\.css$/,It is amended as follows: test: /\.(css|scss|sass)$/,That is to identify the SCSS / sass file

Finally add

React project construction

Configuration alias

Aliases make it easy for us to import files quickly in a project. For example, our project has a common file directory of Src / util / tools, such as the following file structure

├── src                                   
Project resources
│   │   └── ...
Page container
│   │   └── pages
A page a     
│   │           └───a.js                  # a.js           
Other tool classes
│   │   └── tools
│   ├──  index.js                           #Webpack package entry file

Inside the deep-seated componentsa.jsNeed to introducetoolsFile, we’ll use it../../../util/toolsTo find the relative location of the file, but after using the alias configured by webpack, you can locate it directly/srcDirectory.

//Alias not used
import tools from '../../../util/tools';

//After using aliases
Import tools from '@ / util / tools'; //' @ / 'points to' Src / '

collocation method

Both Dev and prod environments need to be configured

Configure in resolve / alias

amongresolveIs a custom function.

function resolve(dir) {
    return path.join(__dirname, '..', dir)

It can also be written as

'@': path.join(__dirname, '..', 'src')

React project construction

Configure hot load

create-react-appThe hot load is configured in the project, we only need to enter the file in the projectindex.jsEnable hot loading on the line, directly add at the end

// index.js
/*Thermal loading*/
if ( {;

React project construction

Configure proxy server

In the front-end development, there are many ways to deal with the cross domain problem. Most webpack is to configure dev_ Server, but this method is invalid in the application generated by create react app package.json On behalf of

// package.json
"proxy": ""

"proxy": {
    "/article": {
      "target": "",
      "changeOrigin": true,
      "secure": false
//The following method has not been configured

Configure routing

The use of react-router4 is different from that of previous versions of router

React-router4 document address

Configure Redux

to configure@connectDecorator

In the project, you can directly access Redux through @ connect

not configured
React project construction

After configuration

React project construction

It should be noted that the decorator is used here and the module needs to be installedbabel-plugin-transform-decorators-legacy

And then in the package.json Inside configurationplugins

React project construction

Configuration of other tools in the project


It is troublesome to switch classnames in react. Trinomial operation can be used for simple operations, but more complicated classes are more troublesome. For example, this slightly more complex div can dynamically switch multiple classnames. A tool library is recommended to switch classnames easily and conveniently

Clsssnames usage document

React project construction

<div className={classNames('clip_item', {
      'clip_active': isActive, 
      'effect_hover': activeDrag === 'video_inner',
       'dragging': is_dragging}
      //Default classname: 'clip_ item'
      //If isactive = = = true, add classname 'clip'_ active'
      // is_ If dragging = = = true, add classname 'dragging'


In the project format time tool library, format the time into any format you want! Very convenient.

Moment(). Format ('mmmm do yyyy, H: mm: ss a '); // September 10, 2018, 7:04:30 PM
Moment(). Format ('dddd '); // Monday
Moment(). Format ("MMM do YY"); // September 10, 18
moment().format('YYYY [escaped] YYYY');     // 2018 escaped 2018
moment().format();                          // 2018-09-10T19:04:30+08:00

moment.js Document address:

Post project optimization

Antd load on demand

Generally, we import the style of the entire UI in CSS according to the usage of the antd official website,@import '~antd/dist/antd.css';
For example, we only use button and table in the project, but in this way, all antd component styles are loaded (which is a hidden danger to the front-end performance);
Therefore, we need to use load on demand, and only load the component styles we have used.

Note: if you run eject and webpack has configured babelrc: false, an error will be reported if you create a new.babelrc in a separate root directory In the module module, loader: require.resolve Add to the plugins array in the (‘babel loader ‘) object

Only the configuration mode that allows eject to expose the webpack configuration file is shown here. Please refer to…

  1. Install Babel plugin import

    npm install --save-dev babel-plugin-import

  2. Add Babel plugin import to Babel loader plugins of webpack

Two files / config need to be modified/ . JS and / config/ . JS (the modified content is the same, and the upgraded create react app is merged into a file webpack.config.js )Add the following code to the loader – begin

    require.resolve ('babel plugin import '), // import the import plug-in
      Libraryname: 'antd', // expose antd
      style: 'css'

The final configuration is as follows (with different versions of create react app, the final configuration may be different, and the principle is the same)

// Process application JS with Babel.
    // The preset includes JSX, Flow, TypeScript, and some ESnext features.
      test: /\.(js|mjs|jsx|ts|tsx)$/,
      include: paths.appSrc,
      loader: require.resolve('babel-loader'),
      options: {
        customize: require.resolve(
        plugins: [
              loaderMap: {
                svg: {
                  ReactComponent: '@svgr/webpack?-svgo,+ref![path]',
          //Antd load on demand
            require.resolve ('babel plugin import '), // import the import plug-in
              Libraryname: 'antd', // expose antd
              style: 'css'
        // This is a feature of `babel-loader` for webpack (not Babel itself).
        // It enables caching results in ./node_modules/.cache/babel-loader/
        // directory for faster rebuilds.
        cacheDirectory: true,
        cacheCompression: isEnvProduction,
        compact: isEnvProduction,

Code separation (react loadable)

A high level component that dynamically imports and loads components

Before use

import Home from'./Home';

After use

import loadable from '@/utils/loadable'
const Home = loadable(() => import('./Home '));

Loadable component

import React from 'react';
import Loadable from 'react-loadable';

//General Assembly
const loadingComponent =()=>{
  return (

//By default, the transition component is general-purpose. If loading is passed in, it will adopt the passed in component
export default (loader,loading = loadingComponent)=>{
  return Loadable({

Reference link

Prerender spa plugin

The construction phase generates HTML files that match the pre rendered path (Note: each route that needs to be pre rendered has a corresponding HTML). The constructed HTML file has some content.

If used simultaneously in the projectCode separationandPreloadingWill cause the page to flash. The reason is that it will load the pre loaded packaged HTML, render the static page, and then request the JS of the page after code separation. This will cause the root node of HTML to mount again. Therefore, code separation with preloading is not recommended.

collocation method

1.npm install prerender-spa-plugin

2. Find/config/

const path = require('path')
const PrerenderSPAPlugin = require('prerender-spa-plugin')

module.exports = {
  plugins: [
    new PrerenderSPAPlugin({
      // Required - The path to the webpack-outputted app to prerender.
      staticDir: path.join(__dirname, '../build'),
      // Required - Routes to render.
      routes: ['/home', '/convert', '/trim', '/merge', '/watermark', '/remove', '/download'],

3. If you need to add a route, add it in routes. At the same time, you need to change the ngnix configuration on the back end

/ -> home/index.html
/home -> home/index.html
/convert -> convert/index.html
/trim -> trim/index.html
/merge -> merge/index.html
/watermark -> watermark/index.html
/remove -> remove/index.html
/download -> download/index.html

Except for the path above, all other paths point to index.html

Multi route pre rendering guide for single page application

Source code

To facilitate the rapid construction of the project, all the configured code in this example is placed in the GitHub project.…

Recommended Today

Blog based on beego, go blog

Go Blog A beego based development, can quickly create personal blog, CMS system Include functions see Official website of go Demo Update log time function January 23, 2020 New top post function February 2, 2020 New custom navigation function February 4, 2020 New site announcement function February 6, 2020 New link module February […]