Recently, I worked on a small project, which was limited to one person for a month. Finally, we hope to launch the application through the wechat public account link. I don’t want to talk about the business details of the project, but I want to share some technical experience of doing this project.

Technology selection

There are three types of references: AngularJS, Angular, React.

There may be some confusion here. Aren’t AngularJS and Angular the same thing?

Yes, they are the same thing, but they are not the same thing. So, without further ado, let’s first explain the difference between AngularJS and Angular.

Quote a sentence from official documentation

Angular is the name for the Angular of today and tomorrow. AngularJS is the name for all v1.x versions of Angular.

namely

Angular: v2.x and later

AngularJS: Specifically v1.x

Since Angular has changed a lot since 2.0, this is the only way to differentiate.

Okay, back to business, how do you choose between these three technologies?

Here’s what I was thinking:

AngularJS: Since we have been using AngularJS for the last two projects, it is not strange to use, and the buffer is much smaller (as mentioned earlier, it is very short, only one month). Run into a problem still can discuss with everybody. But AngularJS performance and size are an issue, especially when running on mobile.

Angular: Performance is not an issue, size is fine. However, I have little contact with them. I have only done one Web project before.

React: I studied it a while back. Performance and size are not an issue. But just like Angular, there is no actual project experience. If something goes wrong, baidu is the only solution.

After weighing the above, I actually wanted to use React in my heart. One of the reasons is that I really want to accumulate some experience in React development through a project after a period of learning. Another reason is that React is more advanced in both performance (thanks to Virtual DOM) and ideology (componentation).

Based on the above two reasons, I strongly recommend React when determining the technology selection with the project manager. Although there may be some buffer, it is considered from the perspective of sustainable development (I guess…). “Finally, the project manager agreed.

Project framework building

I have seen a lot of Boilerplate engineering on GitHub, which is more or less inconsistent with my own needs. Therefore, I eventually built a SEED project through the Create-React-app CLI of React.

1. Prepare the environment

node.js

2. Install the creat-react-app CLI

npm install -g create-react-app
Copy the code

3. Create a project

create-react-app react-seed
Copy the code

Then go to the project root directory react-seed to install the dependencies

cd react-seed
npm install
Copy the code

4. Expose configuration items

The webpack configuration information of the project created using create-react-app is encapsulated. To flexibly modify the configuration, you can run the following command to expose the encapsulated configuration file.

npm run eject
Copy the code

Create the project directory as follows:

5. The local service is started

// Start the local server to develop NPM run startCopy the code

Will start locally on port 3000

Redux integration

If you are familiar with React, you probably know that React is a one-way data flow. Therefore, in some cases, it is impossible for components to communicate with each other only through React. In this case, Redux is needed.

This article does not cover the syntax and ideas of Redux, only how it is integrated.

Redux-related dependencies need to be installed first. Since there may be compatibility issues between different versions, it is best to have a version when installing:

NPM install [email protected] --save NPM install [email protected] --save NPM install [email protected] --saveCopy the code

You can then introduce Redux into your project and organize the directory structure as follows:

Routing integration

react-router

NPM install [email protected] - saveCopy the code

Routing support nesting, code is as follows:

const routes = (
    <Router history= {hashHistory}>
        <Route path="/home" component={Layout} onEnter={onEnter}>
            <IndexRoute getComponent={home} onEnter={onEnter}/>
            <Route path="/home" getComponent={home} onEnter={onEnter}/>
            <Route path="/detect" getComponent={detect} onEnter={onEnter}/>
            <Route path="/about" getComponent={about} onEnter={onEnter}/>
        </Route>
        <Route path="/unauthorized" getComponent={unauthorized}/>
        <Redirect from="*" to="/home" />
    </Router>
);

export default routes;
Copy the code

Internationalization scheme

The common react- intL is used

NPM install [email protected] - saveCopy the code

UI component integration

There are two React UI components recommended here. One is Ant Design. The other one is Material-UI.

Both are good. I use Ant Design.

NPM install [email protected] - saveCopy the code

The fetch integration

There are many ways to request data. I use FETCH.

NPM install [email protected] - saveCopy the code

It can be simply encapsulated as follows:

import 'whatwg-fetch'
import loggerService from './logger'

let notAuthorizedCounter = 0;
let fetchService = {
    fetch: (url, method, header, body) => {
        if(! header) { header = {} }return fetchService[method.toLowerCase()](url, header, body).catch(function(exception) {
            loggerService.log('fetchService failed:', exception); // The token expires. Obtain the token again and initiate a requestif (exception.code === '401' || exception.code === '403') { notAuthorizedCounter++; // Retry a maximum of three timesif (notAuthorizedCounter > 2) {
                    notAuthorizedCounter = 0;
                    loggerService.warn("401 or 403 received. Max attemps reached.");
                    return;
                } else {
                    returnfetchService.fetch(url, method, header, body); }}}); }, get: (url, header) => {return fetch(url, {
            method: 'GET',
            headers: header
        }).then((response) => {
            return response.json();
        });
    },
    post: (url, header, body) => {
        header['Content-Type'] = 'application/json';
        return fetch(url, {
            method: 'POST',
            headers: header,
            body: JSON.stringify(body)
        }).then((response) => {
            returnresponse.json(); }); }};export default fetchService;
Copy the code

Project deployment

First, package the project.

npm run build
Copy the code

You can run the packaged project in your local environment by using the following command.

serve -s build
Copy the code
Note:

The reason is that BrowserRouter uses the browser history object to request the server. If the server does not configure the corresponding route to the corresponding page, the route will not find the resource.

BrowserRouter will become such a path of http://111.230.139.105:3001/detail/9459469, such a path in the access server, the server will be considered a request for an interface data.

So this time must use HashRouter, at that time when accessing a specific page is http://111.230.139.105:3001/#/detail/9459469


The project source has been open source to Github, like to give a Star support! (^_^)

react-seed