Develop a complete set of react project development environment

Time:2020-10-27

In addition to Vue related technologies, react technology stack has also become a necessary technical point for front-end development engineers, whether it is job needs or interview bonus points. Next, I will develop a complete set of react family barrel project development environment from zero, and provide it to peer partners who need to watch it, which is also convenient for me to review later. The length is very long. Please read it patiently and you will get something!

notes

This article comes from
Author: TXM
https://juejin.im/post/5e605d15e51d4526d6406a92

target

What we need to achieve with webpack4. X this time:

  1. Conversion of ES6 / 7 / 8 / 9 and other advanced syntax to Es5
  2. Convert CSS preprocessor such as stylus / less / SCSS to CSS
  3. Parsing font, image (jpg, PNG…) and other static resources
  4. Compress JS, CSS and other files
  5. Automatically add prefix of major browser manufacturers of CSS
  6. Define environment variables
  7. Extract public code
  8. Project hot update and lazy loading
  9. Distinguish production environment from development environment
  10. Delete the last packing record every time you pack
  11. Integration of react, react router DOM, Redux and other surrounding ecology
  12. Add express service interface and connect the front and back end through Axios

Later, the owner integrated the antd UI framework and developed a complete react family barrel project from zero to one line of code.

Project initialization

Check node environment configuration

First install the node environment locally and globally. The operation of react depends onnodeOfnpmTo achieve the management tools, node download address. After downloading the node, open the CMD management tool and enternode -vPress enter to view the node version number. If the version number appears, the installation is successful

node -v npm -v

Develop a complete set of react project development environment

Initialize project directory

On the command line, enter:

MKDIR my react project new project directory
CD my react project / switch to the project directory
NPM init generates some information about the project and eventually generates a package.json Documents. Note: you can enter NPM init – y without pressing enter

Install webpack

Webpack is a module packer, which can automatically analyze the modules that the project depends on and some high-level syntax that the browser can’t directly convert into JS and CSS files that the browser can parse. Install webpack locally in the project root directory. This project will use webpack version 4. X

npm install webpack webpack-cli -D

Develop a complete set of react project development environment

Initializing project directories and files

Create the following file in the project root directory:

SRC: the directory where the source code of the project is stored
index.js : files to be compiled by webpack
Build: store the webpack configuration file of the project
webpack.config.js Project’s webpack core configuration file
index.html : after the project is packaged, the packaged file is automatically added to the file

Develop a complete set of react project development environment

Add basic information of webpack configuration file

  1. Mode: mode, development environment, production production environment
  2. Entry: the packaged entry file of the project
  3. Output: the output file of the project after packaging
  4. Module: module, in webpack, all files are modules, parsing CSS, JS, images and font icons, etc
  5. Plugins: plug-ins, used to extend webpack functions

stay package.json filescriptsProperty to add a runnpm run buildYou can pack it

“build”: “webpack –config ./build/webpack.config.js”

stay index.js Add test code to verify whether the webpack package is correct

function sum(a, b) {
return a + b;
}
var sum = sum(1, 2)
console.log(sum)

If the project dist directory generates a bundle.js File, indicating that the webpack package is correctDevelop a complete set of react project development environment

Configure core functions

Conversion of ES6 / 7 / 8 / 9 and other advanced syntax to Es5

stay index.js Add ES6 / 7 / 8 and other high-level syntax code test code to verify whether webpack can convert it to Es5 and other low-level syntax that the browser can parse

1. Installation related dependencies

npm install babel-loader @babel/core @babel/preset-env -D

Babel loader is to convert high-level syntax such as ES6 into low-level syntax that can be parsed by the browser
@Babel / core is the core module and compiler of Babel. API to provide conversion
@Babel / preset env can automatically convert the code of es2015 + to Es5 according to the target browser or running environment configured
@Babel / preset react for JSX parsing

2. Create in the project root directory babel.config.js file

If you do not create the file, you can also add options to the rules corresponding to the webpack configuration file.

Develop a complete set of react project development environment

3. Modify the core configuration file webpack.config.js file

{
//The files ending in. JS under the SRC directory should be parsed with Babel
//The cachedirectory is used for caching, and the next compilation is accelerated
test: /\.js$/,
use: [‘babel-loader?cacheDirectory=true’],
include: path.join(__dirname, ‘../src’)
},

Then runnpm run buildAs you can see, the advanced syntax we entered, such as ES6 +, is converted to Es5.be careful: Babel loader will only convert high-level syntax such as ES6 / 7 / 8 to Es5 syntax, but not to the new API. Such as promise, iterator, set, proxy, symbol and other global objects, as well as some methods defined on global objects (such as Object.assign )No transcoding. At this point, we have to usebabel-polyfillProvides a gasket for the current environment.

npm install @babel/polyfill -S

Babel Polyfill is to solve the problem that Babel loader cannot convert the new API to add a gasket to the current environment

a key: after we implement the package, the packaged file contains a lot of duplicate code, so we need to provide a unified modular helper to reduce the repeated output of these helper functions.

npm install @babel/runtime @babel/plugin-transform-runtime @babel/plugin-syntax-dynamic-import -D

@Babel / runtime is to provide a unified modular helper, which can greatly reduce the volume after package compilation
@Babel / plugin transform runtime it will help me to automatically dynamic the content in require @ Babel / runtime
Note: there are also some common Babel:
@Babel / plugin proposal decorators transform ES6 + into decorators
@Babel / plugin proposal class properties transforms ES6's more advanced APIs into classes

Develop a complete set of react project development environment

4. In index.js Write ES6 + and other advanced syntax in

let fn = () => {
    console.log ('arrow function ')
}
fn()

let promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(123)
    }, 1000)
})
promise.then(res => {
    console.log(res);
})

Convert CSS preprocessor such as stylus / less / SCSS to CSS

Take the less preprocessor as an example to introduce its usage in detail. The other two are similar:

1. Installation related dependencies

npm install stylus stylus-loader less less-loader sass-loader node-sass css-loader style-loader -D

The main function of CSS loader is to parse CSS files, such as @ import and other dynamic syntax
The main function of style loader is to render the parsed CSS file into the style tag of HTML
Stylus, less and sass are common preprocessors of CSS
Stylus loader, less loader and sass loader mainly convert their corresponding syntax into CSS syntax

2. Modify the core configuration file webpack.config.js

Develop a complete set of react project development environment

3. Add index.less file

@color: red;
#div1 {
    color: @color;
    font-size: 36px;
}

Develop a complete set of react project development environmentbe careful: for many features of CSS3, it is necessary to add various browser compatible prefixes. During the development process, it is too troublesome to add various browser prefixes automatically

npm install postcss-loader autoprefixer -D

Postcss loader autoprefixer handles browser compatibility and automatically prefixes certain properties of CSS3

Develop a complete set of react project development environment

Parsing font, image (jpg, PNG…) and other static resources

Static resources such as pictures and fonts are usually used in the project. If the corresponding loader is not used, an error will be reported

1. Installation related dependencies

npm install file-loader url-loader -D

File loader can be used to help webpack package and process a series of image files, such as. PNG,. JPG,. JEPG, etc. The packaged image will generate a random hash value for each image as its name
URL loader encapsulates the file loader, and its working principles are as follows: 1. If the file size is smaller than the limit parameter, the URL loader will convert the file to Base64; 2. If the file size is larger than the limit, the URL loader will call the file loader for processing, and the parameters will also be passed to the file loader directly

2. Modify the core configuration file webpack.config.js

Develop a complete set of react project development environment

Compress and package JS, CSS and other files

Since a lot of JS files will be generated after the project is packaged, there are many spaces and quotation marks between the codes. If we remove them, it will greatly reduce the packaging volume

1. Installation related dependencies

npm install mini-css-extract-plugin -D
//Or or
npm install  [email protected]  -D // not recommended
npm install optimize-css-assets-webpack-plugin -D
npm install uglifyjs-webpack-plugin -D
//Extend to eliminate unused CSS
npm install purify-webpack purify-css -D

be careful: in production mode, webpack automatically compresses JS. Minicsextractplugin is recommended to be used only in production environment, because the plug-in will lead to the loss of HMR function in the development environment, so style loader is still used in daily development.

2. Modify the core configuration file webpack.config.js

Develop a complete set of react project development environment

Extract public code

After we write the code, we package it, because both CSS and JS have a lot of common parts. If it is not extracted, it will make the packaged project volume too large, affecting the page performance

be careful: after webpack 4, the built-in splitchunkplugin plug-in is used to extract the common part code.

//Core configuration
optimization: {

splitChunks: {
    cacheGroups: {
        //Package common modules
        commons: {
            Chunks: 'initial', // initial means to extract the public part of the entry file
            Minchunks: 2, // indicates the minimum number of files to extract common parts
            Minsize: 0, // indicates the minimum size of the extracted common part
            Name: 'commons' // name of extracted file
        }
    }
}

}

Add resolve option

This option is only added for the convenience of developers, such as file alias, file extension, etc

//Core configuration
resolve: {

extensions: \['.js', '.jsx', '.json'\],
alias: {
    pages: path.join(\_\_dirname, '../src/pages'),
    components: path.join(\_\_dirname, '../src/components'),
    actions: path.join(\_\_dirname, '../src/redux/actions'),
    reducers: path.join(\_\_dirname, '../src/redux/reducers'),
    images: path.join(\_\_dirname, '../src/images')
}

}

Code hot update

1. Installation dependency

npm install webpack-dev-server -D
npm install html-webpack-plugin -D
HTML webpack plugin has two main functions

  1. For the external resources such as script and link introduced in HTML files, the hash after each compile is dynamically added to prevent the problem of referencing the cached external files
  2. You can create HTML entry files

2. Modify the core configuration file webpack.config.js file

Develop a complete set of react project development environment

3. In package.json add to:

“dev”: “webpack-dev-server –config ./build/webpack.config.js”

Delete the last packing record every time you pack

1. Installation related dependencies

npm install clean-webpack-plugin -D

Clean webpack plugin is to delete the folder and file after webpack package

2. Modify the core configuration file webpack.config.js

Develop a complete set of react project development environment

After adding the plug-in, the previous packaging record will be deleted each time you just need to package.

Distinguish production environment from development environment

In our development, both Vue projects and react projects are divided into development environment and production environment. This is because there will be some differences between the two environments:

1、 Development environment:

  1. Module hot update
  2. sourceMap
  3. Interface proxy
  4. Code checking specification

2、 Production environment:

  1. Extract public code
  2. Code compression
  3. Get rid of useless code

Using mode option to distinguish development environment from production environment in webpack

Develop a complete set of react project development environment

Integrate react family barrel

Integrate react steps

1. Installation dependency

npm install react react-dom -S

2. Modification index.js , introduce react

import React from ‘react’;
import ReactDom from ‘react-dom’;

ReactDom.render(

< div > Shi Xiaoming < / div >,
document.getElementById('app')

)

3. NPM run dev run results

Develop a complete set of react project development environment

Integrating react router DOM steps

1. Installation dependency

npm install react-router-dom -S

Add a page folder to the root directory of the project to store the pages, and create two new pages as the files after page Jump

2. Add router.js file

import React from ‘react’
import { Route, Switch } from ‘react-router-dom’

//Import page
import Home from ‘./pages/home/index’
import Page from ‘./pages/page/index’

//Routing
const getRouter = () => {

<Switch>
    <Route exact path="/" component={Home} />
    <Route exact path="/page" component={Page} />
</Switch>

}

export default getRouter;

3. Add a master file

import React from ‘react’
import { Link } from ‘react-router-dom’

export default () => {

return (
    <div>
        <ul>
            <li>< link to = / "> Home Page < / link ></li>
            <li>< link to = / page "> Page Page Page < / link ></li>
        </ul>
    </div>
)

}

Finally, run NPM run dev to see that the two pages can click on each other to jump.

Integrating Redux steps

1. Installation dependency

npm install redux react-redux -S

Redux is a state manager, similar to vuex
React Redux connects Redux and react

2. Create a new core configuration file store

First, create a new core configuration file for the store

import {createStore, combineReducers} from ‘redux’
import counter from ‘reducers/counter’
import userInfo from ‘reducers/userInfo’

let store = createStore(combineReducers({counter, userInfo}))

export default store

Second: integrate the store in the root directory of the project initialization

import ReactDom from ‘react-dom’
import { Provider } from ‘react-redux’

import store from ‘./redux/store’

ReactDom.render(

<Provider store={store}>
    ...
</Provider>,
document.getElementById('app')

)

be careful: by injecting the following component into the store, all files can get the contents of the store

3. Create new actions and reducers folders

be careful: the actions folder stores the behavior, while the reducers folder stores the specific operations

Take counting as an example

First: create a new one in actions counter.js

In this file, we define several types, representing addition, subtraction, and clearing. Then define several action creation functions

//To prevent the type value of action from repeating, add a prefix to the corresponding front
export const INCREMENT = “counter/INCREMENT”
export const DECREMENT = “counter/DECREMENT”
export const RESET = “counter/RESET”

export function increment() {

return {
    type: INCREMENT
}

}
export function decrement() {

return {
    type: DECREMENT
}

}
export function reset() {

return {
    type: RESET
}

}

be careful: when the project is large, we need to store the value of type type in a file for easy management

Second, build a new one in reducers counter.js

In this file, we initialize the initial state and define a specific method for processing logic

import {INCREMENT, DECREMENT, RESET} from ‘../actions/counter’;

//Initialize state
const initState = {

count: 0

}

//The reducer receives two parameters, state, and action returns the new state
export default function reducer(state = initState, action) {

switch (action.type) {
    case INCREMENT:
        return {
            count: state.count + 1
        };
    case DECREMENT:
        return {
            count: state.count - 1
        }
    case RESET:
        return {
            count: 0
        }
    default:
        return state
}

}

be careful: reducer is a pure function that receives the initial value and action and returns a new state. If the corresponding type is not found, the initial value is returned by default

4. Use in project

We create a new counter directory under the page directory to store the directory for testing the Redux function

import React, { Component } from ‘react’
import { connect } from ‘react-redux’
import { increment,decrement, reset } from ‘actions/counter’

class Counter extends Component{

render() {
    return (
        <div>
            <span>The current count value is:{ this.props.counter .count}</span>
            <button onClick={() =>  this.props.increment ()} > added < / button > to
            <button onClick={() =>  this.props.decrement ()} > decrease
            <button onClick={() =>  this.props.reset ()} > Reset < / button >
        </div>
    );
}

}

export default connect(state => state, dispatch => ({

increment: () => {
    dispatch(increment())
},
decrement: () => {
    dispatch(decrement())
},
reset: () => {
    dispatch(reset())
}

}))(Counter)

be careful: react Redux provides a connect method to connect react components with redux.

Through the syntax: connect ([mapstatetoprops], [mapdispatchtoprops], [mergeprops], [options]) to know the meaning of each parameter of the method;

  1. Mapstatetoprops: it means to pass the state state in the store to the component in the way of property props
  2. Mapdispatchtoprops: it means that the disptach method is passed to a component in the form of property props
  3. Mergeprops: not commonly used
  4. Options: not commonly used

Finally, you can execute NPM run dev, and operate the example of digital addition and subtraction on on the interface.

Develop a complete set of react project development environment

Add express service interface and connect the front and back end through Axios

1. Installation dependency

npm install express axios -S

Express Express is based on Node.js A simple and flexible web application development framework based on the platform
Axios is a promise based HTTP network request library

2. Create a new server folder

The modified file is used to store and write the interface that provides foreground call

const express = require(‘express’)
const app = express()

app.get(‘/api/user’, (req, res) => {

res.header('Access-Control-Allow-Origin', '\*')
res.send({
    name: 'tmc',
    age: 24
})

})

app.listen(3000, () => {

console.log('app listen port 3000')

})

3. Start the service

This local service can be started through node, or you can configure a command in webpack to start it.

Execution: node server.js
You can type it in the browser http://localhost : 3000 / API / user to call the interface

4. invoke the interface in the component.

Create a new / home/ test.js Component is used to test the calling interface.

// home/test.js
import React, { Component } from ‘react’
import axios from ‘axios’

export default class Home extends Component{

componentDidMount() {
axios.get('http://localhost:3000/api/user').then(res => {
        console.log(res);
    })
}

render() {
    return (
        <div>
            this is home page.
        </div>
    )
}

}

be careful: when using components to make interface calls, it must be done in the webpack configuration fileCross domainTreatment of

// webpack.dev.config.js

devServer: {

contentBase: path.join(\_\_dirname, '../dist'),
Compress: true, // gzip compression
//Host: '0.0.0.0', // allow IP access
Hot: true, // hot update
Historyapifallback: true, // refresh 404 after solving the problem
port: 8888,
Proxy: {// configure server proxy http://localhost :3000/api/user
    '/api': {
        target: 'http://localhost:3000',
        pathRewrite: {
            '^/api': '/api'
        },
        Changeorigin: true // let target parameter be domain name
        //Secure: false setting supports the HTTPS protocol proxy
    }
}

}

Finally run againnpm run devOpen the browser and load the component just added. You can see the information returned by calling the interface

Develop a complete set of react project development environment

summary

By configuring a complete react project development environment from zero to one line, the most important thing is to use webpack. Knowing and being familiar with the common configuration of webpack is of great benefit to personal ability improvement and job hopping in interview. If you want to improve your partner, you must read it carefully and type it step by step. When you finish, you will get a lot! come on.

Develop a complete set of react project development environment

last

If this article is helpful to you, give it a compliment ❤️❤️❤️

Welcome to join us, learn the front end together and make progress together!Develop a complete set of react project development environment