By coincidence, I wrote the document into the code

Time:2021-9-13

Recently, due to the adjustment of the company’s business, the project needs to develop a large number of business components and high reuse logic for customers. When there are many kinds of components and codes, coupled with the different writing habits and development ideas of several members of the team, many problems arise. In particular, two problems are the most serious:

  1. A large number of business components / business logic need to check the source code or ask the person who wrote the component to know whether the component has its own properties / hook methods
  2. Some components can only be applied to a specific situation because of product requirements + oral communication + demand compromise. Others take them directly when they see the design drawing or logic is almost similar. As a result, they find it useless / various problems

In order to solve these two problems, team members are required to write corresponding development documents / code comments while developing business components. At first, the update of development documents in the middle and later stages obviously couldn’t keep up with the iteration of components, and gradually returned to the situation of asking by mouth. The second question also returned to the starting point over time.

Pass one dayVS CodeWhen debugging the code, I suddenly found that using the mouse in the native syntax andreactHover on the method for a few seconds, and a prompt box will appear with a brief introduction to some nodes / components / methods, parameters, etc.

Yes, that’s what I want!

Native syntax (e.gdocument.getElementById):
document.getElementById

reactMethod (e.guseState):
useState

adoptCTRL + left mouse buttonClick the type definition and find that the content in the prompt box is actually the comment above the relevant code.
类型定义
According to the comments in the type definition, I enter them in the code/**The prompt as shown in the figure below appears when you are.
JSDOC提示

Take the key words and I’ll goVS CodeI searched the official website and found the answer on the official website(Click here )。

VS Code understands many standard JSDoc annotations, and uses these annotations to provide rich IntelliSense.

Vs code can understand standard JSDoc code comments and use these comments to provide rich intelligent perception (such as intelligent code completion, hover information and signature information)

andJSDocThe syntax is also very simple, just make sure that the beginning of the comment is/**Yes, other comments are no different from multiline comments. (more syntax:Click here

/**This creates a code reminder*/
function remind() {}

Try the last component!

import React, { useEffect, useState } from 'react'

interface KeywordInterface {
  /**
   *Key words
   */
  keyword?: string;
  /**
   *The highlighted color supports hex, HSL, RGBA and keywords
   */
  color?: string;
  children?: string;
}

/**
 *Key words高亮组件
 * 
 * @example Hello World
 * 
 *@ param {string} Keyword - Keyword
 *@ param {string} color - highlighted color
 */
const LightKeyword: React.FC = ({
  color = '',
  keyword = '',
  children = ''
}) => {

  const [ context, setContext ] = useState('')

  useEffect(() => {
    //When the keyword is empty, there is no need to highlight the content
    if( !keyword ) { 
      return setContext(children)
    }

    const pattern = new RegExp(keyword, 'gi')
    //Filter out the keywords through regular and add HTML nodes
    const allword = (children as string).replace(pattern, (word) => `${ word }`)

    setContext(allword)
  }, [ keyword, color, children ])

  return (
    
  )
}

export default LightKeyword

Effect display:

When the mouse hovers over a component:
当鼠标悬浮在组件上时

When data is suspended on component properties:
当数据悬浮在组件属性上时

Perfect! In this way, as long as the notes are written according to the format, you can not bother to check the documents.(if you have to write)

What about business logic? So I wrote an asynchronous request code based on business encapsulation.

import qs from 'qs'
import { message } from 'antd'
import axios, { AxiosRequestConfig } from 'axios'

interface configInterface {
  /**
   *Request address
   */
  url: string;
  /**
   *Request mode
   */
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  /**
   *Request parameters
   */
  data?: any;
  /**
   *Other configuration parameters
   * 
   *@ param {object} headers request header configuration
   *@ param {Boolean} ErrorMessage enable error reminders
   *@ param {string} responsetype request type, JSON by default
   *Does @ param {Boolean} withcredentials carry cross domain credentials
   */
  options?: {
    /**
     *Request header configuration
     */
    headers?: any;
    /**
     *Enable error alerts
     */
    errorMessage?: boolean;
    /**
     *The request type is JSON by default
     */
    responseType?: 'json' | 'arraybuffer' | 'blob' | 'document' | 'text' | 'stream';
    /**
     *Carry cross domain voucher
     */
    withCredentials?: boolean
  }
}

//Axios global configuration
const $axios = axios.create({

  //Request interface address
  baseURL: 'https://demo.com',
  //Timeout
  timeout: 60 * 1000
})

/**
 *Asynchronous request
 * 
 *@ description automatically process get request serialization / error code processing feedback / cross domain configuration based on existing business encapsulation
 * @example useRequest({ url: 'api/weather', method: 'GET', data: { date: '2021-02-30' }, options: {} })
 *@ typedef requestconfig request parameters
 *@ param {string} requestconfig.url request address
 *@ param {string} requestconfig.method request method
 *@ param {any} requestconfig.data request parameters
 *@ param {object} requestconfig.options other configuration parameters
 */
const useRequest = async (requestConfig: configInterface): Promise => {

  const requestOptions = requestConfig.options || {}

  const axiosConfig: AxiosRequestConfig = {

    url: requestConfig.url,
    method: requestConfig.method || 'GET',
    headers: requestOptions.headers || {},
    responseType: requestOptions.responseType || 'json',
    withCredentials: requestOptions.withCredentials !== false
  }

  //When the request method is get, the parameters are serialized
  if( axiosConfig.method === 'GET' ) {

    axiosConfig.params = requestConfig.data || {}
    axiosConfig.paramsSerializer = (params) => qs.stringify(params, { arrayFormat: 'brackets' })

  } else {

    axiosConfig.data = requestConfig.data || {}
  }

  try {

    const { data: response } = await $axios(axiosConfig)

    //If the back end returns an error code, push the error into the catch handle for execution
    if( response.code !== 0 ) {

      //Error reminder
      if( requestOptions.errorMessage !== false ) {

        Message. Error (response. Message | 'unknown error')
      }
      
      return Promise.reject(response)
    }

    return Promise.resolve(response)

  } catch(e) {

    //Error reminder
    if( requestOptions.errorMessage !== false ) {

      Message. Error ('request error, please try again later ')
    }

    return Promise.reject(e)
  }
}

export default useRequest

Actual effect:
悬停提示
(basic usage and parameter reminder)
额外配置提醒
(additional configuration reminder)

coordinationTypescript, it’s almost written into the code!!!

But when I built it with interestvue 3Development environment, want to tryvueSmart tips for. After several rounds of testing,JSDocSmart tips are only supported injs/ts/tsxThese types of files are not supported.vueFormat file.
vue文件不支持jsdoc的智能提示
vueFile not supportedjsdoc(smart tips for)

If you want tovueThere are similar intelligent prompts in the file, which can be displayed throughVS CodeinstallveturPlug in, and then create a plug-in namedveturAnd create a new foldertags.jsonandattributes.jsonTwo files, and thenpackage.jsonBoth paths are introduced in.

// package.json
{
  "name": "demo",
  "version": "0.1.0",
  "vetur": {
    "tags": "./vetur/tags.json",
    "attributes": "./vetur/attributes.json"
  }
}

// vetur/tags.json
{
  "light-keyword": {
    "attributes": ["keyword", "content", "color"],
    "Description": "keyword highlighting component"
  }
}

// vetur/attributes.json
{
  "color": {
    "type": "string",
    "Description": "highlighted colors, supporting hex, HSL, RGBA, and keywords"
  },
  "content": {
    "type": "string",
    "Description": "text content"
  },
  "keyword": {
    "type": "string",
    "Description": "Keywords"
  }
}

The final implementation effect
组件智能提示
(component intelligent prompt)
组件描述
(component description)
属性描述
(attribute description)

The advantage is not affectedvueVersion restrictions, 2 and 3 can be used; The downside isjsonFile restrictions, there is no way likeJSDocShow rich formats and code snippets, hopeveturCan strengthen this optimization.