This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!

preface

Since I built the Webpack-Template last time, I have improved a lot of efficiency in the learning after this! No need to build a WebPack environment from scratch, eliminating tedious configuration. However, you will find that our template still has some common plugins/modules not configured, next we will add our configuration items.

If you haven’t read building a WebPack-Template from zero, please follow the link below to read this article

👇 click on me to jump to 👇

🔨🔨 Build a webPack template from scratch with your hand in hand

👆 click on me to jump to 👆

Debugging environment

In real development, it is not always possible to combine projects and open them through the build directive, which makes development and debugging very slow. We provide a plug-in called Webpack-dev-server, which provides us with a temporary server where we can put the packaged files of our project for browsing and debugging.

The installationwebpack-dev-serverThe plug-in
npm install --save-dev webpack-dev-server @types/webpack-dev-server
Copy the code
Configure the plug-in

We need to make some changes to the configuration type. Originally, our configuration object module used the Config type from webPack, but now we need to use another module (webpack-dev-server) to configure the devServer property in the configuration object. The config in WebPack does not have a property of type devServer, so we define a Configuration interface as the Configuration file type, which inherits from the Config in WebPack. When it under devServer WebpackDevServerConfiguration correspond

// webpack.config.ts
// Ignore some code here
import { Configuration as WebpackConfiguration } from 'webpack';
import { Configuration as WebpackDevServerConfiguration } from 'webpack-dev-server';

interface Configuration extendsWebpackConfiguration { devServer ? : WebpackDevServerConfiguration; }// Ignore some code here
Copy the code

In config, add the devServer properties. For more information, see

const config: Configuration = {  
  // Ignore some code here
  devServer: {
    contentBase: path.join(__dirname, 'dist'),
    port: 8080,}}Copy the code

Add serve to the script property in package, JSON, where –open refers to the URL that automatically opens when the service is built

 "scripts": {
    "build": "webpack"."lint": "eslint --fix --ext .js,.ts src"."serve": "webpack serve --open"."prepare": "husky install"
  },
Copy the code

After the NPM Run serve is executed, the Webserver will start to run and build a service environment. The corresponding URL address will also be displayed in the terminal, and the Webserver will automatically help us open the browser to access the corresponding URL address.

Now, when we change some code in the index.html, webpack-dev-server will listen to the changes in the code under the project, immediately repackage and merge the changed code, and the page will be changed accordingly in the updated service.

<! -- src/pages/index/index.html -->
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>index</title>
</head>
<body>
    <h2>
        index.html
    </h2>
<h3>my juejin home page: https://juejin.cn/user/2858385965322935/posts</h3>
</body>
</html>

Copy the code

The webpack-dev-server plug-in has many other configuration items, but we have only done a simple configuration here, if you want to learn more about the configuration, please move to the plug-in configuration document

Network request

In the traditional page, updating the content of the page needs to refresh the whole page, but in the front-end development, it is often inseparable from the network data request, we need to call the back-end written API for data request, rendering the data content into the page. Here we use axios, the third-party request library.

The installationaxios
npm install axios
Copy the code
Direct request (not recommended)

In the simplest way, you can directly use Axios to make a GET/post request to the URL, but this is not recommended. In daily development, we will process the data returned by the request and then give the corresponding component to handle the rendering. If you directly use the following method to request, If your project has a lot of duplicate code per request, you might say that it is not the best way to encapsulate the duplicate code. Axios provides interceptors that process the request before it is sent and the request after the response before it is handed over to the corresponding page. This greatly reduces the coupling of the code and facilitates the maintenance of the code in subsequent development, as well as the centralized management of the API. Read on.

import axios from 'axios'; axios.get(url[, config]).then() axios.post(url[, data[, config]]).. then()Copy the code
Configure the global network request instance

Create the network folder under the SRC folder as the administrative folder for the project’s network requests, create the request.ts file below it, and configure the project’s global AXIos instance.

// src/network/request.ts
// Introduce Axios and some types
import axios, {
  AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosPromise,
} from 'axios';
import responseInterceptor from './Interceptors/responseInterceptor';

export default (config: AxiosRequestConfig):AxiosPromise= > {
// Set global parameters
  const cfg: AxiosRequestConfig = {
    baseURL: 'http://127.0.0.1:8000'.timeout: 5000.headers: {}};const instance: AxiosInstance = axios.create(cfg);

  // Configure the request interceptor
  instance.interceptors.request.use((res: AxiosRequestConfig) = > res);

  // Configure the response interceptor
  // eslint-disable-next-line max-len
  instance.interceptors.response.use((res: AxiosResponse) = > Promise.resolve(responseInterceptor(res)));

  return instance(config);
};
Copy the code

Create the responseinterceptor. ts file in the SRC /network/Interceptors folder and configure the axios instance’s responseInterceptor to handle the data requested from the server.

// src/network/Interceptors/responseInterceptor.ts
import { AxiosResponse } from 'axios';

export default (response: AxiosResponse) => {
  const { status } = response;
  const { errCode } = response.data;
  // If the HTTP response status code response.status is normal, the data is returned directly
  if (status === 200 && errCode === 0) {
    return response.data;
  }
  // When the request status code and the errCode returned by the back end are abnormal
  // Other processing operations
  return errCode;
};
Copy the code
Centralized API management

In the project, we often use a lot of API addresses, we need to manage these in a centralized way, after classifying each API according to the page, we will encapsulate each API into a corresponding API request function, and then we can call the corresponding page to directly get the data processing. Later, if the API address has changed, we can also modify it from the file on the corresponding page, which gives us a great benefit of development!

Create an API folder in the Network folder, where I define a home.ts file as the API management file in the Home page. (This file contains the API functions used in the home page)

// src/network/api/home.ts
import request from '.. /request';

export const getHomeTopNav = () = > request({
  url: '/get_home_top_nav'.method: 'get'});export const homePageArticle = () = > request({
  url: '/home_page_article'.method: 'get'});Copy the code
Using API functions

In the page, we introduce the wrapped API function and wrap it with async await. The requested data will be processed twice in this function, such as case conversion, length segmentation and so on.

import { getHomeTopNav, homePageArticle } from '.. /.. /network/api/home';

const getDataHomeTopNav = async() = > {const res = await getHomeTopNav();
  // Ignore some code
};
const getDataHomePageArticle = async() = > {const res = await homePageArticle();
  // Ignore some code
};

getDataHomeTopNav();
getDataHomePageArticle();
Copy the code

The last

This article is about configuring the debugging environment and network request management for the WebPack-Template that we originally packaged. It is essential to configure the development debugging environment during the daily development of the page, which will make our development experience a little easier. The main purpose of network request encapsulation is to help us simplify the code and facilitate the later update and maintenance.