Vscode智能提示插件怎么用

本篇內(nèi)容主要講解“Vscode智能提示插件怎么用”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“Vscode智能提示插件怎么用”吧!

創(chuàng)新互聯(lián)是一家專業(yè)提供南明企業(yè)網(wǎng)站建設(shè),專注與做網(wǎng)站、網(wǎng)站設(shè)計(jì)、H5開(kāi)發(fā)、小程序制作等業(yè)務(wù)。10年已為南明眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站建設(shè)公司優(yōu)惠進(jìn)行中。

快速查看組件文檔

當(dāng)我們?cè)谑褂?NutUI 進(jìn)行開(kāi)發(fā)的時(shí)候,我們?cè)趯?xiě)完一個(gè)組件 nut-button,鼠標(biāo) Hover 到組件上時(shí),會(huì)出現(xiàn)一個(gè)提示,點(diǎn)擊提示可以打開(kāi) Button 組件的官方文檔。我們可快速查看對(duì)應(yīng)的 API 來(lái)使用它開(kāi)發(fā)。

首先我們需要在 vscode 生成的項(xiàng)目中,找到對(duì)應(yīng)的鉤子函數(shù) activate ,在這里面注冊(cè)一個(gè) Provider,然后針對(duì)定義好的類型文件 files 通過(guò) provideHover 來(lái)進(jìn)行解析。

const files = ['vue', 'typescript', 'javascript', 'react'];

export function activate(context: vscode.ExtensionContext) {
  context.subscriptions.push(
    vscode.languages.registerHoverProvider(files, {
      provideHover
    })
  );
}

下面我們可以具體看看 provideHover 是如何實(shí)現(xiàn)的?

const LINK_REG = /(?<=<nut-)([\w-]+)/g;
const BIG_LINK_REG = /(?<=<Nut-)([\w-])+/g;
const provideHover = (document: vscode.TextDocument, position: vscode.Position) => {
  const line = document.lineAt(position); //根據(jù)鼠標(biāo)的位置讀取當(dāng)前所在行
  const componentLink = line.text.match(LINK_REG) ?? [];//對(duì) nut-開(kāi)頭的字符串進(jìn)行匹配
  const componentBigLink = line.text.match(BIG_LINK_REG) ?? [];
  const components = [...new Set([...componentLink, ...componentBigLink.map(kebabCase)])]; //匹配出當(dāng)前Hover行所包含的組件

  if (components.length) {
    const text = components
      .filter((item: string) => componentMap[item])
      .map((item: string) => {
        const { site } = componentMap[item];

        return new vscode.MarkdownString(
          `[NutUI -> $(references) 請(qǐng)查看 ${bigCamelize(item)} 組件官方文檔](${DOC}${site})\n`,
          true
        );
      });

    return new vscode.Hover(text);
  }
};

通過(guò) vscode 提供的 API 以及 對(duì)應(yīng)的正則匹配,獲取當(dāng)前 Hover 行所包含的組件,然后通過(guò)遍歷的方式返回不同組件對(duì)應(yīng)的 MarkDownString,最后返回 vscode.Hover 對(duì)象。

細(xì)心的你們可能發(fā)現(xiàn)了,這里面還包含了一個(gè) componentMap ,它是一個(gè)對(duì)象,里面包含了所有組件的官網(wǎng)鏈接地址以及 props 信息,它大致的內(nèi)容是這樣的:

export interface ComponentDesc {
  site: string;
  props?: string[];
}

export const componentMap: Record<string, ComponentDesc> = {
    actionsheet: {
        site: '/actionsheet',
        props: ["v-model:visible=''"]
    },
    address: {
        site: '/address',
        props: ["v-model:visible=''"]
    },
    addresslist: {
        site: '/addresslist',
        props: ["data=''"]
    }
    ...
}

為了能夠保持每次組件的更新都會(huì)及時(shí)同步,componentMap 這個(gè)對(duì)象的生成會(huì)通過(guò)一個(gè)本地腳本執(zhí)行然后自動(dòng)注入,每次在更新發(fā)布插件的時(shí)候都會(huì)去執(zhí)行一次,保證和現(xiàn)階段的組件以及對(duì)應(yīng)的信息保持一致。這里的組件以及它所包含的信息都需要從項(xiàng)目目錄中獲取,這里的實(shí)現(xiàn)和后面講的一些內(nèi)容相似,大家可以先想一下實(shí)現(xiàn)方式,具體實(shí)現(xiàn)細(xì)節(jié)在后面會(huì)一起詳解~

組件自動(dòng)補(bǔ)全

我們使用 NutUI 組件庫(kù)進(jìn)行項(xiàng)目開(kāi)發(fā),當(dāng)我們輸入 nut- 時(shí),編輯器會(huì)給出我們目前組件庫(kù)中包含的所有組件,當(dāng)我們使用上下鍵快速選中其中一個(gè)組件進(jìn)行回車,這時(shí)編輯器會(huì)自動(dòng)幫我們補(bǔ)全選中的組件,并且能夠帶出當(dāng)前所選組件的其中一個(gè) props,方便我們快速定義。

這里的實(shí)現(xiàn),同樣我們需要在 vscode 的鉤子函數(shù) activate 中注冊(cè)一個(gè) Provider。

vscode.languages.registerCompletionItemProvider(files, {
    provideCompletionItems,
    resolveCompletionItem
})

其中,provideCompletionItems ,需要輸出用于自動(dòng)補(bǔ)全的當(dāng)前組件庫(kù)中所包含的組件 completionItems

const provideCompletionItems = () => {
  const completionItems: vscode.CompletionItem[] = [];
  Object.keys(componentMap).forEach((key: string) => {
    completionItems.push(
      new vscode.CompletionItem(`nut-${key}`, vscode.CompletionItemKind.Field),
      new vscode.CompletionItem(bigCamelize(`nut-${key}`), vscode.CompletionItemKind.Field)
    );
  });
  return completionItems;
};

resolveCompletionItem 定義光標(biāo)選中當(dāng)前自動(dòng)補(bǔ)全的組件時(shí)觸發(fā)的動(dòng)作,這里我們需要重新定義光標(biāo)的位置。

const resolveCompletionItem = (item: vscode.CompletionItem) => {
  const name = kebabCase(<string>item.label).slice(4);
  const descriptor: ComponentDesc = componentMap[name];

  const propsText = descriptor.props ? descriptor.props : '';
  const tagSuffix = `</${item.label}>`;
  item.insertText = `<${item.label} ${propsText}>${tagSuffix}`;

  item.command = {
    title: 'nutui-move-cursor',
    command: 'nutui-move-cursor',
    arguments: [-tagSuffix.length - 2]
  };
  return item;
};

其中, arguments代表光標(biāo)的位置參數(shù),一般我們自動(dòng)補(bǔ)全選中之后光標(biāo)會(huì)在 props 的引號(hào)中,便于用來(lái)定義,我們結(jié)合目前補(bǔ)全的字符串的規(guī)律,這里光標(biāo)的位置是相對(duì)確定的。就是閉合標(biāo)簽的字符串長(zhǎng)度 -tagSuffix.length,再往前面 2 個(gè)字符的位置。即 arguments: [-tagSuffix.length - 2]

最后,nutui-move-cursor 這個(gè)命令的執(zhí)行需要在 activate 鉤子函數(shù)中進(jìn)行注冊(cè),并在 moveCursor 中執(zhí)行光標(biāo)的移動(dòng)。這樣就實(shí)現(xiàn)了我們的自動(dòng)補(bǔ)全功能。

const moveCursor = (characterDelta: number) => {
  const active = vscode.window.activeTextEditor!.selection.active!;
  const position = active.translate({ characterDelta });
  vscode.window.activeTextEditor!.selection = new vscode.Selection(position, position);
};

export function activate(context: vscode.ExtensionContext) {
  vscode.commands.registerCommand('nutui-move-cursor', moveCursor);
}

vetur 智能化提示

提到 vetur,熟悉 Vue 的同學(xué)一定不陌生,它是 Vue 官方開(kāi)發(fā)的插件,具有代碼高亮提示、識(shí)別 Vue 文件等功能。通過(guò)借助于它,我們可以做到自己組件庫(kù)里的組件能夠自動(dòng)識(shí)別 props 并進(jìn)行和官網(wǎng)一樣的詳細(xì)說(shuō)明。

像上面一樣,我們?cè)谑褂媒M件 Button 時(shí),它會(huì)自動(dòng)提示組件中定義的所有屬性。當(dāng)按上下鍵快速切換時(shí),右側(cè)會(huì)顯示當(dāng)前選中屬性的詳細(xì)說(shuō)明,這樣,我們無(wú)需查看文檔,這里就可以看到每個(gè)屬性的詳細(xì)描述以及默認(rèn)值,這樣的開(kāi)發(fā)簡(jiǎn)直爽到起飛~

仔細(xì)讀過(guò)文檔就可以了解到,vetur 已經(jīng)提供給了我們配置項(xiàng),我們只需要簡(jiǎn)單配置下即可,像這樣:

//packag.json
{
    ...
    "vetur": {
        "tags": "dist/smartips/tags.json",
        "attributes": "dist/smartips/attributes.json"
    },
    ...
}

tags.jsonattributes.json 需要包含在我們的打包目錄中。當(dāng)前這兩個(gè)文件的內(nèi)容,我們也可以看下:

// tags.json
{
  "nut-actionsheet": {
      "attributes": [
        "v-model:visible",
        "menu-items",
        "option-tag",
        "option-sub-tag",
        "choose-tag-value",
        "color",
        "title",
        "description",
        "cancel-txt",
        "close-abled"
      ]
  },
  ...
}
//attributes.json
{
    "nut-actionsheet/v-model:visible": {
        "type": "boolean",
        "description": "屬性說(shuō)明:遮罩層可見(jiàn),默認(rèn)值:false"
    },
    "nut-actionsheet/menu-items": {
        "type": "array",
        "description": "屬性說(shuō)明:列表項(xiàng),默認(rèn)值:[ ]"
    },
    "nut-actionsheet/option-tag": {
        "type": "string",
        "description": "屬性說(shuō)明:設(shè)置列表項(xiàng)標(biāo)題展示使用參數(shù),默認(rèn)值:'name'"
    },
    ...
}

很明顯,這兩個(gè)文件也是需要我們通過(guò)腳本生成。和前面提到的一樣,這里涉及到組件以及和它們關(guān)聯(lián)的信息,為了能夠保持一致并且維護(hù)一份,我們這里通過(guò)每個(gè)組件源碼下面的 doc.md 文件來(lái)獲取。因?yàn)?,這個(gè)文件中包含了組件的 props 以及它們的詳細(xì)說(shuō)明和默認(rèn)值。

組件 props 詳細(xì)信息

tags, attibutes, componentMap 都需要獲取這些信息。 我們首先來(lái)看看 doc.md 中都包含什么?

## 介紹
## 基本用法
...
### Prop

| 字段     | 說(shuō)明                                                             | 類型   | 默認(rèn)值 |
| -------- | ---------------------------------------------------------------- | ------ | ------ |
| size     | 設(shè)置頭像的大小,可選值為:large、normal、small,支持直接輸入數(shù)字   | String | normal |
| shape    | 設(shè)置頭像的形狀,可選值為:square、round            | String | round  |
...

每個(gè)組件的 md 文檔,我們預(yù)覽時(shí)是通過(guò) vite 提供的插件 vite-plugin-md,來(lái)生成對(duì)應(yīng)的 html,而這個(gè)插件里面引用到了 markdown-it 這個(gè)模塊。所以,我們現(xiàn)在想要解析 md 文件,也需要借助于 markdown-it 這個(gè)模塊提供的 parse API.

// Function getSources
let sources = MarkdownIt.parse(data, {});
// data代表文檔內(nèi)容,sources代表解析出的list列表。這里解析出來(lái)的是Token列表。

Token 中,我們只關(guān)心 type 即可。因?yàn)槲覀円氖?props,這部分對(duì)應(yīng)的 Tokentype 就是 table_opentable_close 中間所包含的部分??紤]到一個(gè)文檔中有多個(gè) table。這里我們始終取第一個(gè),*** 這也是要求我們的開(kāi)發(fā)者在寫(xiě)文檔時(shí)需要注意的地方 ***。

拿到了中間的部分之后,我們只要在這個(gè)基礎(chǔ)上再次進(jìn)行篩選,選出 tr_opentr_close 中間的部分,然后再篩選中間 type = inline 的部分。最后取 Token 這個(gè)對(duì)象中的 content 字段即可。然后在根據(jù)上面三個(gè)文件不同的需求做相應(yīng)的處理即可。

const getSubSources = (sources) => {
  let sourcesMap = [];
  const startIndex = sources.findIndex((source) => source.type === TYPE_IDENTIFY_OPEN);
  const endIndex = sources.findIndex((source) => source.type === TYPE_IDENTIFY_CLOSE);
  sources = sources.slice(startIndex, endIndex + 1);
  while (sources.filter((source) => source.type === TR_TYPE_IDENTIFY_OPEN).length) {
    let trStartIndex = sources.findIndex((source) => source.type === TR_TYPE_IDENTIFY_OPEN);
    let trEndIndex = sources.findIndex((source) => source.type === TR_TYPE_IDENTIFY_CLOSE);
    sourcesMap.push(sources.slice(trStartIndex, trEndIndex + 1));
    sources.splice(trStartIndex, trEndIndex - trStartIndex + 1);
  }
  return sourcesMap;
};

好了,以上就是解析的全部?jī)?nèi)容了??偨Y(jié)起來(lái)就那么幾點(diǎn):

1、創(chuàng)建一個(gè)基于 vscode 的項(xiàng)目,在它提供的鉤子中注冊(cè)不同行為的 commandlanguages,并實(shí)現(xiàn)對(duì)應(yīng)的行為

2、結(jié)合 vetur,配置 packages.json

3、針對(duì) map json 文件,需要提供相應(yīng)的生成腳本,確保信息的一致性。這里解析 md 需要使用 markdown-it 給我們提供的 parse 功能。

到此,相信大家對(duì)“Vscode智能提示插件怎么用”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

網(wǎng)頁(yè)名稱:Vscode智能提示插件怎么用
網(wǎng)頁(yè)URL:http://muchs.cn/article38/gpjopp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站改版、自適應(yīng)網(wǎng)站、服務(wù)器托管、企業(yè)建站、品牌網(wǎng)站設(shè)計(jì)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都做網(wǎng)站