A sneak peek

Before we start, what can we learn from this sharing?

  1. Create the React project from zero
  2. Support Sass/Scss/Less/Stylus
  3. React-router-dom is used for routing
  4. Component creation and reference
  5. React Developer Tools browser plugin
  6. Redux and react-redux are used
  7. redux-thunk
  8. Store creation and use
  9. Redux DevTools installation and use
  10. Immutable. Use js
  11. The Mock. Use js
  12. Resolve local cross-domain reverse proxy
  13. Summary of other common tools
  14. Bonus: Integration with Ant Design

Even if you’re new to the React project, you’ll be able to get started quickly.

※ Note: “+” at the beginning of each line in the code area of this article means new, “-” means deleted, and “M” means modified; “… “in code Represents omission.

1 create the React – APP

In order to speed up NPM download speed, first set NPM to Taobao mirror address.

npm config set registry http://registry.npm.taobao.org/
Copy the code

You can also use CNPM, depending on your preference.

Use the official create-react-app to find your favorite directory and run:

npx create-react-app react-app
Copy the code

The react-app at the end of the command is the name of the project, which can be changed.

Wait a moment to complete the installation. After the installation is complete, you can start the project using NPM or YARN.

Go to the project directory and start the project:

cdReact -app yarn start (or use NPM start)Copy the code

If yarn is not installed, you can go to the Yarn Chinese website to install yarn:

yarn.bootcss.com/

Once started, projects can be accessed at the following address:

http://localhost:3000/

2 Thin Projects

2.1 Deleting a File

Next, simplify the project by removing files that are not used in the general project.

├ ─ / node_modules ├ ─ package. Json ├ ─ / public | ├ ─ the favicon. Ico | ├ ─ index. The HTML - | ├ ─ logo192. PNG - | ├ ─ logo512. PNG - | ├ ─ mainfest. Json - | └ ─ robots. TXT ├ ─ README. Md ├ ─ / SRC - | ├ ─ App. CSS | ├ ─ App. Js - | ├ ─ App. Test, js (jTest test automation) - | ├ ─ index. The CSS - | ├ ─ but js - | ├ ─ logo. The SVG - | ├ ─ serviceWorker. Js - | └ ─ setuoTests. Js (PWA) └ ─ yarn. The lockCopy the code

An error message will be displayed after the above files are deleted. This is because the corresponding file reference no longer exists. You need to keep modifying the code.

2.2 Simplifying code

The directory structure is now much cleaner:

├ ─ / node_modules ├ ─ package. Json ├ ─ / public | ├ ─ the favicon. Ico | └ ─ index. The HTML ├ ─ README. Md ├ ─ / SRC | ├ ─ App. Js | └ ─ The index, js └ ─ yarn. The lockCopy the code

Modify the following files one by one:

The SRC/app.js code is simplified as follows:

import React from 'react'

function App() {
  return (
    <div className="App">
      <h1>This is React App.</h1>
    </div>
  )
}

export default App
Copy the code

The SRC /index.js code is simplified as follows:

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'

ReactDOM.render(<App />, document.getElementById('root'))
Copy the code

public/index.html

<! DOCTYPE html> <html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
Copy the code

The running effect is as follows:

2.3 Using Fragments to Remove Outer Labels of Components

React requires that the outermost layer of each component’s HTML be wrapped in a single tag, and that no parallel tags exist. For example, in SRC/app.js, an error is reported if this is the case:

// The following code will report an error, the outermost tag cannot exist parallel.function App() {
  return (
    <div className="App">
      <h1>This is React App.</h1>
    </div>
    <div className="App-other">
      <h1>This is React App-other.</h1>
    </div>
  )
}
Copy the code

If you really need such HTML and don’t want to add a parent tag, you can use fragments as the outermost layer. The code is modified as follows:

M   import React, { Fragment } from 'react'

    function App() {
        return (
+           <Fragment>
                <div className="App">
                    <h1>This is React App.</h1>
                </div>
                <div className="App-other">
                    <h1>This is React App-ohter.</h1>
                </div>
+           </Fragment>
        )
    }

    export default App
Copy the code

This is just to illustrate how fragments work. In some usage scenarios where components are nested, fragments are a good fit. For example, a parent component is

.

and a child component can wrap multiple

with

3 Project directory structure

The project directory structure can be flexibly formulated according to the actual project. Here are my common constructs for reference only.

├ ─ / node_modules ├ ─ package. Json ├ ─ / public | ├ ─ the favicon. Ico < - page icon | └ ─ index. The HTML < - HTML page template ├ ─ README. Md ├ ─ / SRC | ├ ─ / common < - global public directory | | ├ ─ / fonts < - font file directory | | ├ ─ < - image files/images directory | | ├ ─ / js < - public js file directory | | └ ─ / style < -- Common style file directory | | | ├ ─ frame. The CSS < - all public style (import other CSS) | | | ├ ─ reset. CSS < - reset style | | | └ ─ global. The CSS < - global public style | ├ ─ Public module component/components < - directory | | ├ ─ / header < - head navigation module | | | ├ ─ index. The js < - the header master file | | | └ ─ header. The CSS < | - the header style file | └ ─... < - other modules | ├ ─ / pages < - page components directory | | ├ ─ / home < - home page directory | | | ├ ─ index. The js < - home master file | | | └ ─ home. CSS < | - home style file | ├ ─ / login < - login page directory | | | ├ ─ index. The js < - login master file | | | └ ─ the login. The CSS style of < - login file | | └ ─... < - other page | ├ ─ App. Js < - project main module | └ ─ index. The js < - project entry documents └ ─ yarn. The lockCopy the code

3.1 Introduce global common styles

In the frame. Introducing other public in the CSS style: SRC/common/style/frame. The CSS

@import './reset.css';
@import './global.css';
Copy the code

Then add frame.css to SRC /index.js

    import React from 'react'
    import ReactDOM from 'react-dom'
    import App from './App'
+   import './common/style/frame.css'

    ReactDOM.render(<App />, document.getElementById('root'))
Copy the code

As shown, the page global style is in effect.

3.2 support Sass/Less/Stylus

React: How can you use the original CSS? Create-react-app does not expose configuration files by default. To configure projects flexibly, you need to expose configuration files.

Run the following command to expose the configuration file:

※ Note: The operation of exposing configuration files is irreversible!

npm run eject
Copy the code

If you didn’t mention git before, you might get the following error:

Remove untracked files, stash or commit any changes, and try again
Copy the code

You need to run it in the project root directory first:

git add .
git commit -m "Initialize the project (Remarks)"
Copy the code

Wait a moment, eject succeeds and the directory changes as follows:

+ ├ ─ / config + | ├ ─ / jest + | ├ ─ env. Js + | ├ ─ module. The js + | ├ ─ paths. Js + | ├ ─ pnpTs. Js + | ├ ─ webpack. Config. Js < -- Webpack configuration file + | └ ─ webpackDevServer. Config. Js ├ ─ / node_modules ├ ─ package. The json ├ ─ / public | ├ ─ the favicon. Ico | └ ─ Index.html ├ ─ README. Md + ├ ─ / scripts + | ├ ─ build. Js + | ├ ─ start. Js + | └ ─ test. The js ├ ─ / SRC | ├ ─ / common < | - global public directory ├ ─ / components < - public module components directory | ├ ─ / pages < - page components directory | ├ ─ App. Js < - project main module | └ ─ index. The js < - project entry documents └ ─ yarn. The lockCopy the code

3.2.1 support Sass/Scss

After eject, although there is sass code in package.json and webpack.config.js, to use sass /Scss correctly, node-sass needs to be installed again.

Run the following command:

npm install node-sass --save-dev
Copy the code

After the installation is complete, the project supports Sass/Scss. You can change the CSS file name extension to SACC /Scss, and change the frame. CSS file name extension introduced in SRC /index.js to sacC /Scss.

3.2.2 support Less

Install Less and less-loader:

npm install less less-loader --save-dev
Copy the code

Then modify config/webpack.config.js:

// style files regexes const cssRegex = /\.css$/; const cssModuleRegex = /\.module\.css$/; const sassRegex = /\.(scss|sass)$/; const sassModuleRegex = /\.module\.(scss|sass)$/; + const lessRegex = /\.less$/; + const lessModuleRegex = /\.module\.less$/; . (Omitted) // Opt in supportfor SASS (using .scss or .sass extensions).
    // By default we support SASS Modules with the
    // extensions .module.scss or .module.sass
    {
        test: sassRegex,
        exclude: sassModuleRegex,
        use: getStyleLoaders(
            {
                importLoaders: 2,
                sourceMap: isEnvProduction && shouldUseSourceMap,
            },
            'sass-loader'
        ),
        // Don't consider CSS imports dead code even if the // containing package claims to have no side effects. // Remove this when webpack adds a warning or an error for this. // See https://github.com/webpack/webpack/issues/6571 sideEffects: true, }, // Adds support for CSS Modules, but using SASS // using the extension .module.scss or .module.sass { test: sassModuleRegex, use: getStyleLoaders( { importLoaders: 2, sourceMap: isEnvProduction && shouldUseSourceMap, modules: { getLocalIdent: getCSSModuleLocalIdent, }, }, 'sass-loader'),}, // Configure less like sass above. + { + test: lessRegex, + exclude: lessModuleRegex, + use: getStyleLoaders( + { + importLoaders: 2, + sourceMap: isEnvProduction && shouldUseSourceMap, + }, + 'less-loader' + ), + sideEffects: true, + }, + { + test: lessModuleRegex, + use: getStyleLoaders( + { + importLoaders: 2, + sourceMap: isEnvProduction && shouldUseSourceMap, + modules: { + getLocalIdent: getCSSModuleLocalIdent, + }, + }, + 'less-loader'+), +},Copy the code

After the modification, run yarn start to restart the project.

Then change the suffix of the original CSS file to less, frame. Less introduced in SRC /index.js. Less is resolved properly.

3.2.3 support Stylus

Support Stylus exactly the same as Less, first install Stylus and stylus-loader:

Run the following command:

npm install stylus stylus-loader --save-dev
Copy the code

After the installation is complete, modify config/webpack.config.js as described in the previous section to support less. When finished, restart the project and the imported Stylus file can parse properly now.

I have a personal habit of using Stylus, so I will use Stylus in subsequent tutorials. Also, rename the style directory under SRC /common/ to stylus.

├ ─ / config ├ ─ / node_modules ├ ─ package. The json ├ ─ / public ├ ─ README. Md ├ ─ / scripts ├ ─ / SRC | ├ ─ / common < - global public directory | | ├ ─ / fonts | | ├ ─ / images | | ├ ─ / js M | | └ ─ / stylus M | | | ├ ─ frame. The styl M | | | ├ ─ reset. Styl M | | | └ ─ global. Styl | ├ ─ / components < - public module components directory | ├ ─ / pages < - page components directory | ├ ─ App. Js < - project main module | └ ─ index. The js < - project entry documents └ ─ yarn. The lockCopy the code

The frame.styl code looks like this:

@import './reset.styl';
@import './global.styl';
Copy the code

The SRC /index.js code is modified as follows:

    import React from 'react'
    import ReactDOM from 'react-dom'
    import App from './App'
M   import './common/style/frame.styl'

    ReactDOM.render(<App />, document.getElementById('root'))
Copy the code

With the basic configuration done, it’s time to introduce pages. To switch the page, use a Router. Please read the following section.

4 the routing

4.1 Page Construction

First, build the home and login pages.

SRC/pages/home/index. The js code:

import React, { Component } from 'react'
import './home.styl'

class Home extends Component {
    render() {
        return (
            <div className="P-home">
                <h1>Home page</h1>
            </div>
        )
    }
}

export default Home
Copy the code

SRC/pages/home/home. Styl code

.P-home
    h1
        padding: 20px 0
        font-size: 30px
        color: #fff
        background: #67C23A
        text-align: center
Copy the code

SRC/pages/login/index. The js code:

import React, { Component } from 'react'
import './login.styl'

class Login extends Component {
    render() {
        return (
            <div className="P-login">
                <h1>Login page</h1>
            </div>
        )
    }
}

export default Login
Copy the code

SRC/pages/login/login. Styl code

.P-login
    h1
        background: #E6A23C
Copy the code

My personal habit is, fyi:

The global public level (modularization not required) className is g-xxx. Examples include g-autocut and G-color-red.

For page-level className, use p-xxx.

For a module-level className, use m-xxx.

Next, we use react-router-dom to implement routing.

4.2 use the react – the router – the dom

Execute the installation command:

npm install react-router-dom --save
Copy the code

Modify SRC/app.js as follows:

import React, { Fragment } from 'react'
import Login from './pages/login'
import Home from './pages/home'
import { HashRouter, Route, Switch, Redirect } from 'react-router-dom'

function App() {
  return (
    <Fragment>
      <HashRouter>
        <Switch>
          <Route path="/login" component={Login} />
          <Route path="/home" component={Home} />
          <Route exact path="/" component={Home} />
          <Redirect to={"/home"} />
        </Switch>
      </HashRouter>
    </Fragment>
  )
}

export default App
Copy the code

App.js introduces two page-level components, Home and Login. Then use react-router-dom to set the paths separately.

The import mechanism is to look for index.js by default, so the main file name for each component is set to index.js and the file name can be omitted when referenced.



Path means a path, and that’s easy to understand.

Component represents the bound component.

Exact indicates the exact match.

If exact is not set, then:

Localhost :3000/ Will display the Home page,

Localhost :3000/ ABC will also display the Home page.

Because the preceding “/” is matched, the route succeeds.

The

at the end indicates that none of the above matches successfully and the default Redirect is used.

Take a look at the effect:

Visit http://localhost:3000/#/login effects:

Visit http://localhost:3000/#/home effects:

4.3 Route Forwarding

Next, a brief description of how to route between pages.

Add a button to the Login page to jump to the Home page as follows:

    import React, { Component } from 'react'
    import './login.styl'

    class Login extends Component {
        render() {
            return (
               <div className="P-login"> <h1>Login page</h1> + <button onClick={this.gotohome.bind (this)}> Jump Home page</ button> </div>)} +gotoHome() {
+           this.props.history.push('/home') +}}export default Login
Copy the code

Bind (this) in button onClick; otherwise, this in gotoHome is undefined.

Of course, you can also write:

<button onClick={() => {this.gotoHome()}}>Copy the code

The goal is to get this in gotoHome to point to the correct scope.

5 Importing Components

This chapter is also very easy, and those of you who have been exposed to VUE should be well aware that, for the sake of completeness of the tutorial, it is best to keep it brief. Let’s simply implement a common header component.

5.1 Creating the Header Component

The directory structure is as follows:

| ├ ─ / components < - public module components + | | ├ ─ / header < - public header component + | | | ├ ─ index. The js + | | | └ ─ header. The stylCopy the code

SRC/components/headers/index. The js code:

import React, { Component } from 'react'
import './header.styl'

class Header extends Component {
    render() {
        return (
            <div className="M-header">
                Header
            </div>
        )
    }
}

export default Header
Copy the code

SRC/components/headers/header. Styl code:

.M-header
    height: 40px
    line-height: 40px
    font-size: 36px
    color: #fff
    background: #409EFF
Copy the code

5.2 Importing the Header Component

Then, introduce the Header component in the Home and Login pages.

SRC /pages/home/index.js:

    import React, { Component } from 'react'
+   import Header from '.. /.. /components/header'
    import './home.styl'

    class Home extends Component {
        render() {
            return (
                <div className="P-home">
+                   <Header />
                    <h1>Home page</h1>
                </div>
            )
        }
    }

    export default Home
Copy the code

Add the Header component to the Login page in the same way, and the code stays there. The effect is as follows:

5.3 Component Parameter Transfer

Those of you who have used VUE know that the VUE component has data and props. React corresponds to state and props.

React uses the following method to pass parameters to child components:

<Header 
    param1="abc"
    param2="c"
    func1={()=>{console.log('func1')}} / >Copy the code

Inside the Header component, just use this.props to receive. For example, this.props. Param1.

This share mainly introduces the process content. Space is limited. For details about react state and props, please refer to the official documentation.

6 React Developer Tools Browser plug-in

To facilitate the react project debugging, you are advised to install the Chrome plug-in.

Go to the Chrome app store and search for React Developer Tools.

After installing the React project, open the Chrome debugging tool and see the code structure of the React project.

Project making

All the project codes involved in this sharing have been uploaded to GitHub. Students who need them can download them by themselves:

Github.com/Yuezi32/rea…

Please read the next part

This sharing (part 1) has come to an end. In the next chapter, we will continue to explain the following contents:

7 Redux and related plug-ins

  • 7.1 installation redux

  • 7.2 install the react – story

  • 7.3 installation redux – thunk

  • 7.4 Installing the Browser Redux plug-in

  • 7.5 create the store

  • 7.6 Store decomposition of complex projects

  • 7.7 Interconnecting react-Redux with store

  • 7.8 Starting Redux DevTools

  • 7.9 Using immutable for Installation

8 Mock. Js installation and use

9 Resolve cross-domain problems in local development

10 Other common tools

Bonus chapter: Integrating Ant Design

  • 11.1 Installing Ant Design

  • 11.2 Load on demand

  • 11.3 Customizing Theme Colors

Please read:

Build React projects from scratch (part 2)

Please pay attention to my personal wechat official number and get the latest articles at any time.