Preface: This is an article that has been gathering dust in the draft box for a long time

Initialize the project

Create a project

mkdir xxx
cd xxx
Copy the code

Initialize the Git repository

git init
Copy the code

Yarn initialization

#You can use NPM or YARN as package management based on your preference
yarn init
Copy the code

Second, code normalization

Here we use EditorConfig + Prettier + ESLint + StyleLint to constrain code normalization.

Benefits:

  • Constraining team members for readability and maintainability problems caused by code irregularities.
  • Resolve coding specification inconsistency caused by different editors.
  • Identify code style problems in advance, and give corresponding specification tips, timely repair.
  • Reduce the back-and-forth modification process during code review and save time.
  • Automatic formatting, unified coding style.

EditorConfig configuration

EditorConfig solves the problem of inconsistent coding styles among IDE editors. Editorconfig website

Add.editorConfig to the project root directory with the following contents:

# Editor configuration, See http://editorconfig.org # root = true [*] # all files applicable charset = UTF-8 # utF-8 Indent_style = space # indented style (TAB | space) indent_size = 2 # # end_of_line indentation size = lf control line type (lf | cr | CRLF) Trim_trailing_whitespace = true # Insert_final_newline = true # Always insert a newline at the end of the file [*.md] # indicates that the following rules apply only to MD files max_line_length = off trim_trailing_whitespace = falseCopy the code

Prettier configuration

Prettier supports JS, TS, CSS, SCSS, Less, JSX, TSX, React, Angular, Vue, GraphQL, JSON, Markdown, Prettier is a powerful code formatting tool for Prettier

1. Install the prettier

yarn add prettier -D
Copy the code

2. Create the Prettier configuration file in the root directory

The. Prettierrc file (where Prettier supports configuration files in various formats, such as. Json,. Yml,. Yaml,.js, etc.) is used in this project.

{
  "useTabs": false,
  "tabWidth": 2,
  "printWidth": 100,
  "singleQuote": true,
  "trailingComma": "es5",
  "bracketSpacing": true,
  "semi": true,
  "arrowParens": "avoid",
  "jsxBracketSameLine": false
}
Copy the code

3. Now that Prettier is installed and configured, you can format your code with the following command

#Format all files (. Means all files)
npx prettier --write .
Copy the code

ESLint configuration

ESLint is no stranger to anyone. The core of ESLint is to analyze code, check code quality, and provide repair capabilities by matching patterns on the parse AST (Abstract Syntax Tree).

1. Install ESLint

yarn add eslint -D
Copy the code

2. Configure ESLint Run NPX ESLint –init to create the configuration file as prompted by terminal operations.

  • How would you like to use ESLint?

  • What type of modules does your project use?

  • Which framework does your project use?

  • Does your project use TypeScript?

  • Where does your code run?

  • How would you like to define a style for your project?

  • Which style guide do you want to follow?

  • What format do you want your config file to be in?

  • Would you like to install them now with npm?

We chose TypeScript as the template for the above operations, and we need to add TypeScript dependencies as well

yarn add typescript -D
Copy the code

Eslintrc. js configuration file will be automatically generated in the root directory of the project after the operation is complete. You can configure the.eslintrc.js configuration file as required.

module.exports = {
  env: {
    browser: true.es6: true,},extends: ['plugin:react/recommended'.'airbnb'].parser: '@typescript-eslint/parser'.parserOptions: {
    ecmaFeatures: {
      jsx: true,},ecmaVersion: 12.sourceType: 'module',},plugins: ['react'.'@typescript-eslint'].rules: {
    'import/no-extraneous-dependencies': ['error', { devDependencies: true}].'import/extensions': 'off'.'import/no-unresolved': 'off'.'react/jsx-filename-extension': 'off'.'no-use-before-define': 'off'.'@typescript-eslint/no-use-before-define': 'off',}};Copy the code

8. Resolve the conflict between Prettier and ESLint,Prettier Configuration rule > ESLint configures rules

“ESLint –fix” ESLint –fix “ESLint –fix” ESLint –fix “ESLint –fix” ESLint –fix “ESLint –fix” ESLint –fix “eslint-plugin-prettier” eslint-config-prettier” ESLint would format code according to Prettier’s configuration, easily resolving the conflict between the two.

  • Eslint-plugin-prettier Sets the rule of Prettier into the rule of ESLint.

  • Eslint-config-prettier Disables a rule in ESLint that conflicts with Prettier.

1. Install the plug-in

eslint-plugin-prettier eslint-config-prettier -D
Copy the code

2. Add the prettier plug-in in.eslintrc.js

module.exports = {
  ...
  extends: [
    "plugin:react/recommended"."airbnb"."plugin:prettier/recommended",],... }Copy the code

StyleLint configuration

StyleLint is a powerful, modern CSS code detection tool that helps us avoid styling errors through a range of code styles.

1. Install the StyleLint dependency
yarn add stylelint stylelint-config-standard stylelint-scss stylelint-order stylelint-config-recess-order -D
Copy the code

stylelint-scss

SCSS extension to add support for SCSS syntax

stylelint-config-standard

Official code style: stylelint-config-standard. The maintainers of Stylelint draw on the strengths of GitHub, Google, and Airbnb to create the style.

stylelint-order

The purpose of this plugin is to force you to write CSS in a certain order. For example: write positioning first, then write box model, then write content area style, and finally write CSS3 related properties. This can greatly ensure the readability of our code, as follows:

A. Position display float left Top right bottom Overflow Clear Z-index

B. Own attributes: Width height padding border margin background

C. Text style: font-family font-size font-style font-weight font-varient color

D. Text attributes: text-align vertical-align text-wrap text-transform text-indent text-decoration letter-spacing word-spacing white-space text-overflow

E. Css3 added content box-shadow border-RADIUS transform

stylelint-config-recess-order

Third-party configuration of the Stylelint-Order plug-in

2. Configure the StyleLint file

Create the.stylelintrc.js configuration file in the root directory with the following contents:

module.exports = {
  extends: ['stylelint-config-standard'.'stylelint-config-recess-order'].plugins: ['stylelint-scss'.'stylelint-order'].ignoreFiles: ['**/*.js'.'**/*.ts'].rules: {
    'at-rule-no-unknown': [true, { ignoreAtRules: ['mixin'.'extend'.'content'.'include']}],'scss/at-rule-no-unknown': true,}};Copy the code

Integrate Husky and Lint-staged

This project has integrated ESLint and Prettier, but still there will be a part of the developers in the process of encoding a blind eye to the above specification, submit the format is not standard code to remote warehouse, so we need to add some constraints, so that didn’t pass inspection, repair code prohibits submitted, to ensure the code of the warehouse is in conformity with the specification. Git hooks were used to further constrain specifications, which were done using Husky and Lint-staged hooks

1. The configuration of husky

You can quickly initialize the husky configuration using the husky-init command (I won’t go into details about what husky-init does here).

npx husky-init && yarn
Copy the code

Husky contains a number of hooks, including pre-commit, commit-msg, and pre-push. Here, we use pre-commit to trigger the ESLint command.

2. Configuration lint – staged

Lint-staged commands can be programmed into Husky hook fired commands that only act on files in Git staging (that is, files that Git add) without affecting other files.

1. Install

yarn add lint-staged -D
Copy the code

2. Include Lint-staged configuration items in package.json (since this project uses TypeScript encoding and is designed to package React components, JS, TS, JSX, and TSX will be constrained)

"lint-staged": {
    "**/*.{js,ts,jsx,tsx}": [
      "eslint --fix"]."**/*.{css,scss}": [
      "stylelint --fix"]}Copy the code

3. Change the.husky/pre-commit hook trigger command to NPX lint-staged

3. Standardization of submission

We have unified the code specification through the above operations and restricted the code submission to ensure the quality of the warehouse. However, when some developers submit the code in team collaboration, the submission information is not specific enough, disordered, and the style is not consistent. Standardize git commit information, so that the later maintenance and Bug handling become documented, but also according to the standard submission information can quickly generate development logs, so that we can track the project and control the progress. Here we take the dominant community specification: the Angular team submission specification.

Commit Message specification

Commit Message consists of Header, Body, and Footer.

Header

The Header section contains three fields type (required), Scope (optional), and subject (required).

<type>(<scope>): <subject>
Copy the code
type

Type indicates the commit type of the commit (it must be one of the following).

scope

Scope indicates the scope of the impact of this commit, which can be determined according to the project, for example, divided by function modules and menus. The component library developed here can be divided by components

subject

Subject describes the commit content. The length must be no more than 50 characters. Subject generally complies with the following specifications:

  • Verb beginning, first person present tense
  • The first letter is lowercase
  • Ending without a period (.)
Body

The Body is a detailed description of this commit, which can be divided into multiple lines. It should explain the reason for this change and the comparison before and after the change (the Body can be omitted).

Footer

When this submission is for a BREAKING CHANGE update, or a major defect has been resolved, the footer is required, otherwise it can be omitted.

Specification:

  • BREAKING CHANGE Footer begins with BREAKING CHANGE, followed by a description of the CHANGE and the reasons for it.

  • Closing defects If the current submission is for a specific issue, you can fill in the Footer section for a single issue or series of issues to close.

2. Commitizen integration

Now that we’ve covered the commit specification, let’s use Commitizen to help us automatically generate commit messages that conform to the specification

Install Commitizen
yarn add commitizen -D
Copy the code
Cz – customizable initialization

Initialize the project through the CZ-Customizable adapter

npx commitizen init cz-customizable -D -E
Copy the code

Create the.cz-config.js file in the root directory, and then follow the official provided example to configure it.

module.exports = {
  // Type type (after defined, can be selected by up or down keys)
  types: [{value: 'feat'.name: 'Feat: New Features' },
    { value: 'fix'.name: 'fix: fix bugs' },
    { value: 'docs'.name: 'docs: Document changes' },
    { value: 'style'.name: 'style: code format (does not affect functionality, such as Spaces, semicolons, etc.) ' },
    { value: 'refactor'.name: 'Refactor: Code refactoring (excluding bug fixes, feature additions)' },
    { value: 'perf'.name: 'PERF: Performance Tuning' },
    { value: 'test'.name: 'test: Add and modify test cases' },
    { value: 'build'.name: 'Build: Build process, external dependency changes (e.g. upgrading NPM package, modifying Webpack configuration, etc.)' },
    { value: 'ci'.name: 'CI: Modify CI configuration, script' },
    { value: 'chore'.name: 'chore: Changes to the build process or helper tools and libraries (without affecting source files, test cases) ' },
    { value: 'revert'.name: 'revert: rollback commit'},].// Scope type (after defined, select by up or down key)
  scopes: [['components'.'Component correlation'],
    ['hooks'.'hooks related'],
    ['utils'.'utils related'],
    ['styles'.'Style dependence'],
    ['cli'.'Scaffold related'],
    ['deps'.'Project dependencies'],
    ['other'.'Other Modifications'],
    ['custom'.'None of the above? I want to customize. '],
  ].map(([value, description]) = > {
    return {
      value,
      name: `${value.padEnd(30)} (${description}) `}; }),// Is scope allowed to be customized? When scope is selected, empty and custom can be selected.
  allowCustomScopes: false.// Interactive prompts
  messages: {
    Type: 'Make sure this submission follows the specification! \n Select the type you want to submit: '.scope: '\n Select a scope (optional) : '.// Select scope: custom to display the following prompt
    customScope: 'Please enter custom scope:'.Subject: 'Fill in short, concise change description: \n'.Body: 'Fill in a more detailed change description (optional). The use of "|" line: \ n '.Breaking: 'List major changes that are incompatible (optional) : \n'.footer: 'Lists the ISSUES CLOSED of all changes (optional). For example: #31, #34: \n'.confirmCommit: 'Confirm submission? ',},// Set the breaking Message query to feat or fix for type
  allowBreakingChanges: ['feat'.'fix'].// Skip the steps to be asked
  skipQuestions: ['body'.'footer'].// subject limits the length
  subjectLimit: 50.breaklineChar: '|'.// Support body and footer
  // footerPrefix : 'ISSUES CLOSED:'
  // askForBreakingChangeFirst : true,
};

Copy the code

Git commit -m “XXX” can be done with git Cz, and will automatically generate a canonical commit message based on the terminal input information.

Commitlint validates the commit specification

Use @commitLint/config-Conventional and @commitLint/CLI to add restrictions on submitting code

Install @commitlint/ config-Conventional and @commitlint/cli

yarn add @commitlint/config-conventional @commitlint/cli -D
Copy the code

Create a file named commitlint.config.js in your project root directory and fill it with the following contents:

module.exports = { extends: ['@commitlint/config-conventional']}Copy the code

We use the husky command to create a commit- MSG file in the.husky directory and execute the commit message validation command there.

npx husky add .husky/commit-msg "npx --no-install commitlint --edit $1"
Copy the code

Ending, thanks for reading!