Due to the recent adjustment of the company’s business, the project needs to develop a large number of business components and high reuse logic for customers to use. When there are more components and codes, and several members of the team have different writing habits and development ideas, there are a lot of problems. In particular, two problems are the most serious:

  1. A lot of business components/business logic need to look at the source code, or ask the person who wrote the component, to know if the component has the property/hook methods it needs
  2. Some components can only be applied to a specific situation due to product requirements + verbal communication + requirement compromise, and other people take them directly when they see the design drawing or the logic is almost similar, only to find it can’t be used/various problems

In order to solve these two problems, team members began to be required to write corresponding development documents/code comments while developing business components. At first it was fine, but the mid-to-late development document updates were clearly not keeping up with the component iterations, and gradually it was back to the mouth, with the second question coming back to the starting point over time.

One day while debugging with VS Code, I noticed that hovering over the native syntax and React methods for a few seconds brought up a prompt box with a brief description of nodes/components/methods, parameters, etc.

Yeah, that’s what I wanted!

Native syntax (e.g. Document.getelementbyid) :

React methods (e.g. UseState) :

Click CTRL + left mouse button on the type definition to find that the content in the prompt box is actually a comment above the relevant code.

Following the comments in the type definition, I was prompted to type /** in the code as shown below.

I went to the VS Code website and found the answer (click here).

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

VS Code understands standard JSDoc Code comments and uses them to provide rich intellisense (such as intelligent Code completion, hover information, and signature information)

JSDoc’s syntax is very simple, just make sure the comment starts with /**, and is no different than a multi-line comment. (For more grammar: click here)

/** this creates a code alert */
function remind() {}
Copy the code

Write a component on it and try it!

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

interface KeywordInterface {
  /** ** key */keyword? : string;/** * Highlight the color, support hex, HSL, RGBA, keywords */color? : string; children? : string; }/** * keywords highlight components **@example <LightKeyword keyword="hello">Hello World</LightKeyword>
 * 
 * @param { string } keyword- Key words *@param { string } color- Highlight the color */
const LightKeyword: React.FC<KeywordInterface> = ({
  color = ' ',
  keyword = ' ',
  children = ' '
}) = > {

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

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

    const pattern = new RegExp(keyword, 'gi')
    // Use the re to filter out the keywords and add HTML nodes
    const allword = (children as string).replace(pattern, (word) = > `<i class="light-keyword-item" ${ color && `style="color: ${ color }"` }>${ word }</i>`)

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

  return (
    <span className="light-keyword" dangerouslySetInnerHTML={{ __html: context}} ></span>)}export default LightKeyword
Copy the code

Effect display:

When the mouse hovers over a component:

When data floats over component properties:

Perfect! This way, you can save yourself the hassle of looking up the document if you just format your comments. (If you have to write)

What about business logic? So I wrote a piece of 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 }  Configure the headers request header *@param { boolean } ErrorMessage Whether to enable error notification *@param { string }  ResponseType Request type, default is JSON *@param { boolean } WithCredentials Whether the withCredentials carry cross-domain credentials */options? : {/** * Request header configuration */headers? : any;/** * Whether to enable error notification */errorMessage? : boolean;/** * Request type, default is json */responseType? :'json' | 'arraybuffer' | 'blob' | 'document' | 'text' | 'stream';
    /** * Whether to carry cross-domain credentials */withCredentials? : boolean } }// Axios global configuration
const $axios = axios.create({

  // Request the interface address
  baseURL: 'https://demo.com'.// The timeout period
  timeout: 60 * 1000
})

/** * asynchronous request **@description Automatic handling of GET request serialization/error code handling feedback/cross-domain configuration based on existing business encapsulation *@example useRequest<T>({ url: 'api/weather', method: 'GET', data: { date: '2021-02-30' }, options: {} })
 * @typedef RequestConfig Specifies the request parameter *@param   { string } Requestconfig. url Specifies the request address *@param   { string } Requestconfig. method Request method *@param   { any }    Requestconfig. data Request parameters *@param   { object } Requestconfig. options Other configuration parameters */
const useRequest = async <T>(requestConfig: configInterface): Promise<T> => {

  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
  }

  // Serialize the parameters when the request is GET
  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 to execute
    if( response.code ! = =0 ) {

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

        message.error(response.message || 'Unknown error')}return Promise.reject(response)
    }

    return Promise.resolve(response)

  } catch(e) {

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

      message.error('Request error, please try again later')}return Promise.reject(e)
  }
}

export default useRequest
Copy the code

Actual effect:

(Basic usage and parameter reminder)

(Extra configuration reminder)

Working with Typescript, you almost write documentation into your code!!

However, as I excitedly set up the development environment for VUE 3, I wanted to try out vue’s smart tips. After several rounds of testing, JSDoc smart prompt only supports js/ TS/TSX files, but does not support. Vue files.

(VUE files do not support JSDoc smart tips)

If you want similar smart tips in your vue files, you can install the vetur plugin with VS Code, create a folder called vetur in your project root directory, and create two new files, tags. Json and attributes. Json. Then introduce the paths to both in package.json.

// package.json
{
  "name": "demo"."version": "0.1.0 from"."vetur": {
    "tags": "./vetur/tags.json"."attributes": "./vetur/attributes.json"}}// vetur/tags.json
{
  "light-keyword": {
    "attributes": ["keyword"."content"."color"]."description": "Keyword highlight component"}}// vetur/attributes.json
{
  "color": {
    "type": "string"."description": "Highlighted colors, support hex, HSL, RGBA, keywords"
  },
  "content": {
    "type": "string"."description": "Textual content"
  },
  "keyword": {
    "type": "string"."description": "Keywords"}}Copy the code

The final implementation effect

(Intelligent reminder of components)

(Component Description)

(Attribute Description)

The advantage is that the vUE version is not limited, 2 and 3 can be used; The downside is that json files are limited, and there is no way to display rich formats and code snippets like JSDoc. Hopefully Vetur can improve this optimization.