preface

This is the fifth article in the Webpack Study Notes series. Please click here for the first four articles:

  • If you meet me for the first time, please give me your advice
  • Webpack Study Notes ii: Basic property management
  • Webpack Study Notes (3) : Environment configuration
  • Webpack 5+ React

In this article, we will build a complete full-stack project configuration template using the project from Note 4 as the base project. Let’s take a look at our technology selection:

  • The back-end server of the project was set up and express was selected
  • In the database of the project, mongoDB is selected, and Mongoose is used to operate the database
  • React was chosen to build the front end of the project
  • For project packaging, choose webpack5

Actually engineering and construction requirements

Initial project template

Before explaining the construction process of the project, let’s take a look at what the construction project looks like in article 4. The basic information of the project is in its package.json file, which is as follows:

{
  "name": "webpack-react-demo"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
    "dev": "webpack-dev-server --config config/webpack.dev.config.js"."build": "webpack --config config/webpack.prod.config.js"."test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": []."author": ""."license": "ISC"."devDependencies": {
    "@babel/core": "^ 7.14.3"."@babel/plugin-transform-runtime": "^ 7.14.3"."@babel/preset-env": "^ 7.14.4"."@babel/preset-react": "^ 7.13.13"."babel-loader": "^ 8.2.2"."clean-webpack-plugin": "^ 4.0.0 - alpha."."css-loader": "^ 5.2.6." "."happypack": "^ 5.0.1." "."html-webpack-plugin": "^ 5.3.1"."mini-css-extract-plugin": "^ 1.6.0." "."open-browser-webpack4-plugin": "^ 1.0.0"."sass-loader": "^ 12.0.0"."webpack": "^ 5.38.1"."webpack-cli": "^" 3.3.12."webpack-dev-server": "^ 3.11.2"."webpack-merge": "^ 5.7.3." "
  },
  "dependencies": {
    "react": "^ 17.0.2"."react-dom": "^ 17.0.2"}}Copy the code

In this code you can get the following information:

  • The server used for development is webpackwebpack-dev-server
  • The project completes the basicsbabelconfiguration
  • The development environment and production environment of the project are separate, and the script commands required at runtime are respectivelynpm run devandnpm run build
  • This project can load CSS resources

The desired result

  • Express + Webpack-dev-middleware is used instead of Webpack-dev-server
  • The React project can implement hot replacement
  • Express + Mongoose was used to build the background server
  • Nodemon starts the background server for real-time updates
  • The scripts command separates the front and back end packaging, running, and development commands

Set up process

  • Replace webpack – dev – server

    Implementing this substitution is simple, specifically removing the dev-server-related; Then, install Express and Webpack-dev-middleware and write the servser.js file
    1. Uninstall webpack dev – server:
    npm uninstall webpack-dev-server
    Copy the code
    1. delete./webpack.config.jsThe webpack-dev-server configuration is as follows:
     devServer: {
        contentBase: concatPath('.. /app'),
        historyApiFallback: false.hot: false.host: '0.0.0.0'.port: PORT,
    },
    Copy the code
    1. Install Express and Webpack-dev-Middleware
    NPM install --save-dev webpack-dev-middleware // Express needs to be used in two places, one is a front-end development server, and the other is a back-end development server, so it cannot be installed in the development. npm install --save expressCopy the code
    1. Add it under the root directory./server.js:
    const express = require('express');
    const webpack = require('webpack');
    const webpackDevMiddleware = require('webpack-dev-middleware');
    
    const app = express();
    const config = require('./webpack.config.js');
    const compiler = webpack(config);
    
    // Tell Express to use webpack-dev-middleware,
    // And use the webpack.config.js configuration file as the base configuration.
    app.use(
      webpackDevMiddleware(compiler, {
        publicPath: config.output.publicPath,
      })
    );
    
    // Serve the file to port 3000.
    app.listen(3000.function () {
      console.log('Example app listening on port 3000! \n');
    });
    Copy the code
  • The react hot replacement

    The React hot replacement process consists of the following three steps:
    1. Install related plug-ins
    npm install --save react-router react-router-dom
    npm install --save-dev webpack-hot-middleware react-hot-loader
    Copy the code
    1. Changing a Configuration file

    ./server.jsAdd to file

    const webpackHotMiddleware = require('webpack-hot-middleware');
    app.use(webpackHotMiddleware(compiler))
    Copy the code

    To change the./webpack.config.jsThe entrance

    entry: {
        index: [
          'react-hot-loader/patch'.'webpack-hot-middleware/client'.'babel-polyfill'.'./src/index.js'].vendor: ['react'.'react-dom']},Copy the code

    ./webpack.config.jsAdd a newly referenced plug-in to the file:

    plugins: [
        new webpack.HotModuleReplacementPlugin(),
    ],
    Copy the code
    1. in./index.jsReceive hot replacement in file

    ./index.jsAdd:

    if(module.hot){
        module.hot.accept()
    }
    Copy the code
  • Express Background Construction

    Add the following code to the express package:
    import express from 'express'
    
    // Create a background server application
    const app =  new express()
    
    // Listen on the port
    app.listen(3030.(err) = > {
        if(err){
            console.log('err:', err)
        } else {
            console.info(`===> api server is running at loaclhost:3030`)}})// Port test
    app.get('/test'.(req,res) = > {
        res.send('API server created successfully!! ')})Copy the code

    You then add the necessary plug-ins and the operations you need to perform to access a particular route as required.

  • Nodemon starts the background

    Just install Nodemon and change the startup command
    npm install --save-dev nodemon
    Copy the code
  • Scripts command writing

    This is where you need to separate the development environment from the production environmentpackage.jsonAdd the following command to the file:
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"."watch-client": "cross-env NODE_ENV=development node ./server/index.js"."watch-client-prod": "cross-env NODE_ENV=production node ./server/index.js"."start-dev-api": "nodemon --watch server/api server/api/index.js"."build-client": "cross-env NODE_ENV=production webpack --config webpack.prod.js"."dev": "npm run watch-client & npm start-dev-api"."build": "npm run build-client & npm run watch-client-prod & npm run start-dev-api"
      },
    Copy the code

    In this way, the NPM command can be used to run the project, package, compile and other operations.

Type on the blackboard and underline

At the end, there are a few caveats to this process

  • The front-end development server is not the same as the back-end server
  • Development environment and production environment need to be separated: development environment needs to solve the problem of how to facilitate development and debugging; The production environment needs to solve the problem of project optimization
  • Nodemon is mainly convenient for background development and debugging. It has nothing to do with the front-end server and cannot be confused