溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Vscode智能提示插件怎么用

發(fā)布時間:2022-05-13 09:05:46 來源:億速云 閱讀:279 作者:iii 欄目:軟件技術(shù)

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

快速查看組件文檔

當(dāng)我們在使用 NutUI 進行開發(fā)的時候,我們在寫完一個組件 nut-button,鼠標(biāo) Hover 到組件上時,會出現(xiàn)一個提示,點擊提示可以打開 Button 組件的官方文檔。我們可快速查看對應(yīng)的 API 來使用它開發(fā)。

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

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

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

下面我們可以具體看看 provideHover 是如何實現(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) ?? [];//對 nut-開頭的字符串進行匹配
  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) 請查看 ${bigCamelize(item)} 組件官方文檔](${DOC}${site})\n`,
          true
        );
      });

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

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

細心的你們可能發(fā)現(xiàn)了,這里面還包含了一個 componentMap ,它是一個對象,里面包含了所有組件的官網(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=''"]
    }
    ...
}

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

組件自動補全

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

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

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

其中,provideCompletionItems ,需要輸出用于自動補全的當(dāng)前組件庫中所包含的組件 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)前自動補全的組件時觸發(fā)的動作,這里我們需要重新定義光標(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ù),一般我們自動補全選中之后光標(biāo)會在 props 的引號中,便于用來定義,我們結(jié)合目前補全的字符串的規(guī)律,這里光標(biāo)的位置是相對確定的。就是閉合標(biāo)簽的字符串長度 -tagSuffix.length,再往前面 2 個字符的位置。即 arguments: [-tagSuffix.length - 2]。

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

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 官方開發(fā)的插件,具有代碼高亮提示、識別 Vue 文件等功能。通過借助于它,我們可以做到自己組件庫里的組件能夠自動識別 props 并進行和官網(wǎng)一樣的詳細說明。


像上面一樣,我們在使用組件 Button 時,它會自動提示組件中定義的所有屬性。當(dāng)按上下鍵快速切換時,右側(cè)會顯示當(dāng)前選中屬性的詳細說明,這樣,我們無需查看文檔,這里就可以看到每個屬性的詳細描述以及默認值,這樣的開發(fā)簡直爽到起飛~

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

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

tags.jsonattributes.json 需要包含在我們的打包目錄中。當(dāng)前這兩個文件的內(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": "屬性說明:遮罩層可見,默認值:false"
    },
    "nut-actionsheet/menu-items": {
        "type": "array",
        "description": "屬性說明:列表項,默認值:[ ]"
    },
    "nut-actionsheet/option-tag": {
        "type": "string",
        "description": "屬性說明:設(shè)置列表項標(biāo)題展示使用參數(shù),默認值:'name'"
    },
    ...
}

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

組件 props 詳細信息

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

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

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

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

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

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

拿到了中間的部分之后,我們只要在這個基礎(chǔ)上再次進行篩選,選出 tr_opentr_close 中間的部分,然后再篩選中間 type = inline 的部分。最后取 Token 這個對象中的 content 字段即可。然后在根據(jù)上面三個文件不同的需求做相應(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;
};

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

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

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

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

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

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI