takeaway

Learn content: This article mainly learn snowpack, React, TS, react-router and other libraries and plug-ins application

Learning Achievements:

  1. You will get a taste of Snowpack
  2. Learn how to configure Sass in Snowpack
  3. How do I debug the simulation interface using RAP2
  4. How do I encapsulate the FETCH request
  5. How do I access environment variables and encapsulate configuration files
  6. How to check your code before git commit

Audience: Those who have some knowledge of JavaScript, React, and packaging tools

Difficulty: ⭐⭐⭐

Snowpack

Next time you pack, why pack

What is snowpack? Quote from the official website

Snowpack is a lightning-fast frontend build tool, designed for the modern web. It is an alternative to heavier, more complex bundlers like webpack or Parcel in your development workflow. Snowpack leverages JavaScript’s native module system (known as ESM) to avoid unnecessary work and stay fast no matter how big your project grows.

Once you try it, it’s impossible to go back to anything else.

Snowpack is a lightning-fast front-end build tool designed for modern networks. It can replace heavier, more complex bundlers like Webpack or Parcel in your development workflow. Snowpack leverages JavaScript’s native module system (called ESM) to avoid unnecessary work and stay fast no matter how big your project grows.

Once you try it, it’s impossible to go back to anything else.

Simply put, Snowpack 🐂🍺!

Now all you need to know is how to install, create a folder, and execute the following code in that directory

npm install --save-dev snowpack
Copy the code

OK, finished

React

The only opponent, is the last oneself

React is a library of JavaScript wizardry used to build user interfaces. It works like magic

TypeScript

Snap, snap, snap

People are more familiar with TypeScript, and as your code grows, TypeScript becomes more valuable

Quick start

Run the following code to quickly create a React + TypeScript snowpack base template project

npx create-snowpack-app react-snowpack --template @snowpack/app-template-react-typescript
Copy the code

For more templates click here

After the installation, execute the following code and the service will be up and running in less than 50ms

npm run start
Copy the code

React Router

All roads lead to Rome

After entering the React-Snowpack file, execute the following code to install the React Router

npm install react-router-dom
Copy the code

NPM install react-router In fact, react-router-DOM is encapsulated on the basis of react-router, which is more convenient to use

After installing react-router-dom, VS CODE will prompt you that the corresponding description file is missing

npm install @types/react-router-dom -D
Copy the code

Sass

Style, but also this style

To configure SASS, first install snowpack’s Sass plug-in

npm install @snowpack/plugin-sass -D
Copy the code

Then configure the Sass plug-in in the snowpack.config.js file

plugins:[....,
	'@snowpack/plugin-sass',]Copy the code

All you need to do is create a.scSS file and test it

Note: If you are running Windows, you may need to configure the Python environment first

RAP2

Future interface, debug now

RAP2 provides you with handy interface documentation, mocks, exports, etc. It’s easy to debug with virtual data when no real interface is available

  1. Log in
  2. Creating an interface
  3. Debug in the browser

Above operation is too simple, not described in this article, don’t want to, you can directly request rap2api.taobao.org/app/mock/28… This example

fetch('http://rap2api.taobao.org/app/mock/284263/example/1622281098808');
let json = await fetch('http://rap2api.taobao.org/app/mock/284263/example/1622281098808');
console.log(await res.json());
Copy the code

Fetch

Gently, fall in love again

Fetch can be explained here

Fetch is an upgraded version of XMLHttpRequest and is provided natively by browsers. Using FETCH directly reduces dependencies, makes our code smaller, and reduces the maintenance cost of our code

Here we simply encapsulate fetch to intercept request and response. There are five parameters: URL for the address requested, method for the request, data for the data requested, headers for the custom header that you will use when downloading a file using a BLOB, cancelToken for whether to remove the user’s authentication for better compatibility. You can modify the logic based on your actual development design

import config from ".. /config/index";
// Platform return type
class XYXResponse {
  code: number = 200;
  data: object = {};
}
const baseUrl = config.baseUrl;
const defaultHeaders = { "Content-Type": "text/plain; charset=UTF-8" };
const request = async (
  url: string,
  method: string, data? : object, headers? : object,cancelToken: boolean = false,
) => {
  let requestUrl = baseUrl + url;
  letoption: RequestInit = {}; option.method = method; option.headers = { ... defaultHeaders, ... headers };if(! cancelToken) { option.headers.token =localStorage.getItem("token") | |"";
  }
  if (data) {
    if (method.toUpperCase() === "GET") {
      // Deconstruct the argument to convert the object to a URL argument
      let params = "";
      for (const [key, value] of Object.entries(data)) {
        if(value ! = =undefined&& value ! = =null) {
          params += `${key}=${value}& `;
        }
      }
      requestUrl = `${requestUrl}?${params}`;
    } else {
      option.body = JSON.stringify(data); }}// Send the request
  let response = await fetch(requestUrl, option);
  // Process the result
  if (response.ok) {
    let result: XYXResponse = await response.json();
    if (result.code === 401) {
      // If the authentication fails, the token is cleared and redirected to the login page
      console.log("Not certified");
      localStorage.setItem("token"."");
    } else {
      returnresult; }}else {
    throw new Error(response.statusText); }};export default request;
Copy the code

How do I configure files in different environments

You can easily access environment variables using the following code

import.meta.env.MODE;
Copy the code

When NPM runs start, the default MODE value is development. When NPM runs build, the default MODE value is production. Of course you can refer to the Snowpack file to customize more information.

You can use different configuration files according to the MODE value. See the following operations

  1. Create config folder
  2. Create index.ts, development.ts, and production.ts in the config folder
  3. Create a common configuration in index.ts
  4. Create the development environment configuration in development.ts
  5. Create the production environment configuration in production.ts
  6. In index.ts, import the corresponding configuration based on the MODE value, merge it with the common configuration, and finally export it

Reference code

index.ts

import devConfig from "./development";
import proConfig from "./production";

class EnvConfig { baseUrl? : string ="";
}
const mode = import.meta.env.MODE;
let commonConfig = {};
let config: EnvConfig = {};
if (mode === "development") { config = { ... commonConfig, ... devConfig }; }else if (mode === "production") { config = { ... commonConfig, ... proConfig }; }export default config;
Copy the code

development.ts

export default {
  baseUrl: "http://rap2api.taobao.org/app/mock/data"};Copy the code

production.ts

export default {
  baseUrl: "proBaseUrl"};Copy the code

The idea is actually the same as Webpack

Husky

To submit? something

Husky is a Git hook tool that allows you to perform certain actions before or after a code submission. Husky is very simple to use. For example, 🌰

  1. Add “prepare”: “husky install” to the scripts TAB of package.json

  2. Run NPM run prepare

  3. Add a hook that performs a code formatting check before submitting the code, which is already configured by default in the template

    npx husky add .husky/pre-commit "npm run lint"
    Copy the code
  4. At this point, you change the code in a mess, and then save, commit, and find that the commit failed

  5. You need to run NPM run format to format the code before it can be submitted

The end of the

Now you have a simple, practical scaffold! Don’t you want to like it, Old Iron?