Create a project development environment of front and back end separation with React+Flask

Article directory

Preface

In the new year, the first technical paper on water will be started. As it happens, React has been playing a lot recently. Please write an article to commemorate the construction of development environment. A kind of
Original text: Create a project development environment of front and back end separation with React+Flask

  • Two questions at the beginning:
    • What is React? : React, the JavaScript library used to build the user interface (official website copy and paste, really fragrant, no need to write template, comfortable
    • What is Flask? : a lightweight Web application framework written in Python. Used to write Cloud native application Very fragrant!

First look at the final project structure, as follows: Project source code

├── app.py
├── env
|  ├── Include
|  ├── Lib
|  ├── LICENSE.txt
|  ├── Scripts
|  └── tcl
├── frontend
|  ├── build
|  ├── node_modules
|  ├── package-lock.json
|  ├── package.json
|  ├── public
|  ├── README.md
|  └── src
├── static
|  └── js
└── templates
   └── index.html

Development environment: Windows+Flask+React+Git Bash+vscode

Backend-Flask

I prefer to use CLI, So. Project development depends on using virtualenv+pip management, pipenv It's OK, though lock package is a little long. I heard it's relatively new poetry Very fragrant?

# 1. Install virtualenv
pip install virtualenv
# 2. Create a virtual environment for a project (flask react) - > env
virtualenv env
# 3. Activate virtual environment env
source env/Scripts/activate
# 4. Installation project dependency
pip install -r requirments.txt
# 5. Create templates and static directory to store the packaged rendering templates and static files of React
mkdir templates
mkdir static

After the basic environment of back-end service is set up, write a route to see if you can use it first

# app.py
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return "<h1>Hello React+Flask!</h1>"

if __name__ == '__main__':
    app.run('127.0.0.1', port=5000, debug=True)

Frontend-React

The development environment of the front-end React application uses the official scaffold create-react-app Build up.

# 1. Installation of scaffolding
npm install -g create-react-app
# 2. Create react app - > frontend for the flash ﹣ react project
create-react-app frontend # It's a little bit long here. Have a cup of coffee and touch the fish

OK, the front-end development environment is set up, all files under the src directory are cleaned up, and a component is written by yourself, as follows:

cd frontend/src
rm -rf *
touch index.js
//index.js
import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
    render() {
        return (
            <div className="container">
                <h1 className="center-align">
                    //Disadvantages of box packing<br/>
                    <span className="waves-effect waves-light btn">
                        <i className="material-icons right">cloud</i>You are right
                    </span>
                </h1>
            </div>
        );
    }
}

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

OK, preview the effect, and debug by the way (nothing to debug / (Fei o Fei) / ~). npm start. The effect is as follows:

If it's not a big problem, it's time to package and write the React App for back-end services.

Done

It's very comfortable create-react-app With Babel and webpack encapsulated, we can directly use npm run build to package and write the App into the frontend/build directory. Then manually move the generated files to Flask's templates and static Directory. Wait? Manually, can I use CLI, dang however.

npm allows us to use the scripts field to customize Script commands in the package.json file. More comfortable is that npm script provides pre and post hooks. We can provide two hooks for the build Script command: prebuild and postbuild. The Script command of the edited package.json file is as follows:

  "scripts": {
    "start": "react-scripts start",
    "prebuild": "rm -rf ..\\templates\\index.html && rm -rf ..\\static",
    "build": "react-scripts build",
    "postbuild": "mv build\\index.html ..\\templates\\ &&  mv build\\static ..\\static",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

At this time, when we execute the npm run build command, we will automatically execute it in the following order

rm -rf ..\\templates\\index.html && rm -rf ..\\static
react-scripts build
mv build\\index.html ..\\templates\\ &&  mv build\\static ..\\static

OK, let's try. As follows:

Nice, no problem. 🎉🎉🎉. Change app.py:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')  # Rendering pages of packaged React App

if __name__ == '__main__':
    app.run('127.0.0.1', port=5000, debug=True)


No problem! End of work!!!

References

14 original articles published, 7 praised, 3607 visited
Private letter follow

Tags: React npm JSON pip

Posted on Mon, 13 Jan 2020 04:41:06 -0500 by pitn