Notes on front-end engineering

1 Introduction

At work, do we often encounter the following situations:

  • Do we find it very painful to take over the code of other colleagues, such as: indentation, line breaks, etc. Code styles that once made us feel uncomfortable
  • A colleague mentioned a code that often reported syntax errors. The syntax errors could only be reviewed one by one with the naked eye, without any prompts.
  • Colleagues each write their commits in a different style, and some are lazy. They write it in one word, but they don’t describe the category of this change. For example: Is it adding a function? Is it code optimization? Or fix bugs? Or modify the webpack configuration? Or modify the tool chain, etc.
  • If it is a monorepo warehouse, there are many projects in it, and if you write a commit randomly and don't care which project is changed, will it be very crashing?

Regarding code syntax checking, code formatting, commit comment specifications, code compilation, etc., these are complicated and huge hard work, unless you don't want to treat people like horses, then you should leave it to the machine, right?

The front-end field is no longer the pure js and jquery era of the past. Modularization and engineering have also become the pursuit of the front-end field, so as to ensure the readability, maintainability, robustness, etc. of the front-end program.

2.Background

Front-end engineering has been developing for some years, and a large number of efficiency-improving packages have sprung up like mushrooms after a rain. So as a small front-end person, I couldn't help but explore it. After all, no one wants to work crazy overtime and be treated like a horseman, and I also want to get off the morning shift and start a simple and happy life.

This article aims to record the practical process of exploring basic front-end engineering, so that you can read it later, please lighten it (ps: this article focuses on code inspection, code beautification, and commit specifications, including the use of chatgpt)

The basic technology selection of the project is: react + ts, so the basic configuration of front-end engineering will be carried out based on this.

3.Git hook: husky

husky is a tool for running commands in Git hooks. It can automatically trigger specified commands on specific events such as code commits or pushes. Through husky, you can run scripts in scenarios such as before code submission, after submission, and before push to perform code style inspection, unit testing, construction, etc.

Installation is as follows:

  1. Download the npm package of husky
  2. Initialize husky
  3. Automatically initialize husky when configuring npm install

Use shortcut commands to complete the above installation steps

# npm
npx husky-init && npm install

# yarn
yarn dlx husky-init --yarn2 && yarn

#pnpm
pnpm dlx husky-init && pnpm install

4. File filtering tool: lint-staged

lint-staged is a tool for running specified commands on git staged files. It can help you perform code style checking, formatting, static analysis and other operations on the files to be submitted before submitting the code, so as to maintain the quality and consistency of the code before submitting it.

The basic usage is as follows:

1. Install dependencies

# npm
npm install lint-staged --save-dev

#yarn 
yarn add lint-staged --dev

#pnpm
pnpm add lint-staged --save-dev

2. Modify the package.json file as follows:

{
  "scripts": {
    "lint": "eslint src"
  },
  "lint-staged": {
    "src/**/*.{ts,tsx}": [
      "npm run lint", // 运行自定义的 lint 脚本
      "git add" // 添加修复后的文件到暂存区
    ]
  }
}

The above configuration means: for all files with suffixes ts and tsx in the src directory, the npm run lint command will be run to perform syntax checking before submission, and then the repaired files will be added to the staging area.

During actual development, lint-staged will generally cooperate with the pre-commit hook to perform actions before commit, so we replace the pre-commit hook content as follows:

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npx lint-staged

5.Commit comment specification: commitlint

commitlint is a tool for normalizing Git commit messages. It helps the team ensure that each commit message conforms to unified specifications to improve the readability and maintainability of the code warehouse

Here we directly show the use of commitlint with husky

1. Install related dependencies

# npm
  npm install @commitlint/cli @commitlint/config-conventional --save-dev

  # yarn
  yarn add @commitlint/cli @commitlint/config-conventional --dev

  # pnpm
  pnpm add @commitlint/cli @commitlint/config-conventional --save-dev

2. Use husky to add commit-msg hook

npx husky add .husky/commit-msg 'npx --no -- commitlint --edit "$1"'

3. In the commitlint information in the package.json file, the 11 annotation types provided by commitlint are used by default (ps: you can customize it, such as ui and version below)

{
  "commitlint": {
    "extends": [
      "@commitlint/config-conventional"
    ],
    "rules": {
      "type-enum": [
        2,
        "always",
        [
          "build",
          "chore",
          "ci",
          "docs",
          "feat",
          "fix",
          "perf",
          "refactor",
          "revert",
          "style",
          "test",
          "ui",
          "version"
        ]
      ]
    }
  }
}

The 11 annotation types provided by commitlint are explained as follows:

  • build: Compilation-related modifications, such as: release version, project build tool changes, etc. (for example: glup, rollup, webpack, vite, turbo and other tools)
  • chore: miscellaneous modifications (for example: changing the build process, adding dependent libraries, etc.)
  • ci: Continuous integration related modifications (for example: github-action, gitlab-ci/cd, etc.)
  • docs: Document modification
  • feat: new features
  • fix: fix bug
  • perf: optimization (for example: improving performance, experience, etc.)
  • refactor: code refactoring
  • revert: rollback version
  • style: code format modification
  • test: test case modification

6. Code inspection

Code inspection uses eslint, typescript-eslint

eslint is a tool for checking and fixing JavaScript code errors, style and quality issues. It can help developers and teams follow consistent coding standards during the coding process, improving code readability, maintainability and quality.

typescript-eslint is a tool for inspecting and repairing TypeScript code. It is based on eslint and provides a set of rules and plugins to check and fix errors, style and quality issues in TypeScript code.

In summary, the following packages need to be installed in the development environment:

  1. eslint
  2. eslint-plugin-react-hooks
  3. eslint-plugin-react-refresh
  4. @typescript-eslint/parser
  5. @typescript-eslint/eslint-plugin
# npm
npm install eslint eslint-plugin-react-hooks eslint-plugin-react-refresh @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev

# yarn
yarn add eslint eslint-plugin-react-hooks eslint-plugin-react-refresh @typescript-eslint/parser @typescript-eslint/eslint-plugin --dev

# pnpm
pnpm add eslint eslint-plugin-react-hooks eslint-plugin-react-refresh @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev

The basic steps to use eslint are as follows:

  1. Install eslint: Run the command npm install eslint --save-dev or yarn add eslint --dev or pnpm add eslint --save-dev in the project root directory to install eslint into the project as a development dependency.
  2. Initialize the eslint configuration file: Run the command eslint --init in the project root directory, select configuration options according to the prompts, and the configuration file (usually .eslintrc or .eslintrc.json) will be automatically generated
  3. Add rules and plug-ins: In the generated configuration file, you can add or modify rules according to project needs, and introduce required plug-ins.
  4. Run eslint: Run eslint yourfile.js or eslint . in the command line, where yourfile.js is the file name or directory that needs to be checked. eslint will check the code according to the configuration file and output error or warning information
  5. Automatic repair: Run eslint --fix yourfile.js or eslint --fix. You can try to automatically fix some of the fixable problems.

The basic steps to use typescript-eslint are as follows:

1. Install typescript-esLint: Run the following command in the project root directory

#npm 
npm install @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev

# yarn
yarn add @typescript-eslint/parser @typescript-eslint/eslint-plugin --dev

#pnpm
pnpm add @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev

2. Configure eslint and @typescript-eslint plug-ins: In the generated eslint configuration file, you need to specify the parser as @typescript-eslint/parser, and use the rules and plug-ins provided by @typescript-eslint/eslint-plugin

The eslint configuration file is as follows (take .eslintrc as an example):

module.exports = {
  root: true,
  env: { browser: true, es2020: true },
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:react-hooks/recommended',
  ],
  ignorePatterns: ['dist', '.eslintrc.cjs'],
  parser: '@typescript-eslint/parser',
  plugins: ['react-refresh'],
  rules: {
    'react-refresh/only-export-components': [
      'warn',
      { allowConstantExport: true },
    ],
    '@typescript-eslint/ban-ts-comment': 'off'
  }
}

The following is the code inspection command combined with lint-staged configuration:

{
  "scripts": {
    "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "lint:fix": "eslint . --ext ts,tsx --fix",
  },
  "lint-staged": {
    "*.(ts|tsx)": [
      "eslint --quiet"
    ]
  }
}

7. Code beautification: prettier

Prettier is a code formatting tool that can automatically adjust the format of code to conform to a unified style specification.

The basic usage is as follows:

1. Install dependencies

# npm 
npm install prettier --save-dev

# yarn
yarn add prettier --dev

#pnpm
pnpm add prettier --save-dev

2. To configure prettier, you can use the prettier field in the .prettierrc file or package.json file. The following takes package.json as an example:

{
  "prettier": {
    "trailingComma": "all",
    "arrowParens": "always",
    "printWidth": 120
  }
}

In actual application, the code will be beautified before commit. The following is the code inspection + code beautification command combined with lint-staged configuration:

{
  "prettier": {
    "trailingComma": "all",
    "arrowParens": "always",
    "printWidth": 120
  },
  "lint-staged": {
    "*.(ts|tsx)": [
      "eslint --quiet"
    ],
    "*.(ts|tsx|json|html)": [
      "prettier --write"
    ]
  }
}

8. Recommend a development tool

About low-code being very active in the tech world right now!

What is low code? A set of digital technology tool platforms can realize rapid construction, data orchestration, connection ecology, middle-end services, etc. based on more efficient methods such as graphical drag and drop and parameterized configuration. Achieve scenario application innovation in digital transformation with little or no code. It can alleviate or even solve the contradiction between supply and demand caused by huge market demand and traditional development productivity. It is a product of the trend of cost reduction and efficiency improvement in the process of digital transformation.

Here we introduce a useful low-code platform - JNPF rapid development platform. In recent years, it has been outstanding in terms of market performance and product competitiveness. It adopts the latest mainstream front-to-back separation framework (SpringBoot+Mybatis-plus+Ant-Design+Vue 3 ) . The code generator has low dependency and flexible expansion capabilities, allowing for flexible secondary development.

In order to support application development with higher technical requirements, the enterprise-level low-code platform represented by JNPF has almost no difference from traditional software development from database modeling, Web API construction to page design. It only uses low-code visualization mode to reduce the construction cost. The "Add, Delete, Modify and Check" function is a repetitive work. Partners who have not yet understood low-code can try to understand it.

Application: https://www.jnpfsoft.com/?csdn

With it, developers can easily get started during the development process and make full use of the experience accumulated in the traditional development model. Therefore, low-code platforms are of great help to programmers.

Guess you like

Origin blog.csdn.net/Z__7Gk/article/details/132989256