• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Vscode智能提示插件nutui-vscode-extension

武飞扬头像
PHP中文网
帮助54

直观体验

什么是代码智能提示?为了让大家有一个直观的认识,让我们先来仔细观察下面两张 gif 图~

组件库没有任何的代码提示

学新通技术网

组件库有了智能提示之后

学新通技术网

不知大家在看了上面两张图片之后有什么样的感想?很明显,我们使用了智能提示之后,无论是快速查看文档,还是查看组件属性,都会很方便的进行查阅,当然开发效率上肯定也有了显著的提升。那么,让我们快来亲自体验下吧~

学新通技术网

使用指南

  • vscode 中安装 nutui-vscode-extension 插件

学新通技术网

  • 安装 vetur 插件。不了解这个插件的这里有介绍

学新通技术网

安装完成以上两个插件之后,重新启动我们的 vscode ,就可以愉快的体验 NutUI 的智能提示功能啦,是不是简直不要太简单~

熟悉了基本的 vscode 开发流程之后,下面就跟随我一步步揭开这个智能提示功能的神秘面纱吧~

360全方位解读

学新通技术网

快速查看组件文档

学新通技术网

从上图可以看出,当我们在使用 NutUI 进行开发的时候,我们在写完一个组件 nut-button,鼠标 Hover 到组件上时,会出现一个提示,点击提示可以打开 Button 组件的官方文档。我们可快速查看对应的 API 来使用它开发。

首先我们需要在 vscode 生成的项目中,找到对应的钩子函数 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 是如何实现的?

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); //根据鼠标的位置读取当前所在行
  const componentLink = line.text.match(LINK_REG) ?? [];//对 nut-开头的字符串进行匹配
  const componentBigLink = line.text.match(BIG_LINK_REG) ?? [];
  const components = [...new Set([...componentLink, ...componentBigLink.map(kebabCase)])]; //匹配出当前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 以及 对应的正则匹配,获取当前 Hover 行所包含的组件,然后通过遍历的方式返回不同组件对应的 MarkDownString,最后返回 vscode.Hover 对象。

细心的你们可能发现了,这里面还包含了一个 componentMap ,它是一个对象,里面包含了所有组件的官网链接地址以及 props 信息,它大致的内容是这样的:

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 这个对象的生成会通过一个本地脚本执行然后自动注入,每次在更新发布插件的时候都会去执行一次,保证和现阶段的组件以及对应的信息保持一致。这里的组件以及它所包含的信息都需要从项目目录中获取,这里的实现和后面讲的一些内容相似,大家可以先想一下实现方式,具体实现细节在后面会一起详解~

组件自动补全

学新通技术网

我们使用 NutUI 组件库进行项目开发,当我们输入 nut- 时,编辑器会给出我们目前组件库中包含的所有组件,当我们使用上下键快速选中其中一个组件进行回车,这时编辑器会自动帮我们补全选中的组件,并且能够带出当前所选组件的其中一个 props,方便我们快速定义。

这里的实现,同样我们需要在 vscode 的钩子函数 activate 中注册一个 Provider

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

其中,provideCompletionItems ,需要输出用于自动补全的当前组件库中所包含的组件 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 定义光标选中当前自动补全的组件时触发的动作,这里我们需要重新定义光标的位置。

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代表光标的位置参数,一般我们自动补全选中之后光标会在 props 的引号中,便于用来定义,我们结合目前补全的字符串的规律,这里光标的位置是相对确定的。就是闭合标签的字符串长度 -tagSuffix.length,再往前面 2 个字符的位置。即 arguments: [-tagSuffix.length - 2]

最后,nutui-move-cursor 这个命令的执行需要在 activate 钩子函数中进行注册,并在 moveCursor 中执行光标的移动。这样就实现了我们的自动补全功能。

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 的同学一定不陌生,它是 Vue 官方开发的插件,具有代码高亮提示、识别 Vue 文件等功能。通过借助于它,我们可以做到自己组件库里的组件能够自动识别 props 并进行和官网一样的详细说明。

vetur详细介绍看这里

https://vuejs.github.io/vetur/guide/component-data.html#workspace-component-data

学新通技术网

像上面一样,我们在使用组件 Button 时,它会自动提示组件中定义的所有属性。当按上下键快速切换时,右侧会显示当前选中属性的详细说明,这样,我们无需查看文档,这里就可以看到每个属性的详细描述以及默认值,这样的开发简直爽到起飞~

仔细读过文档就可以了解到,vetur 已经提供给了我们配置项,我们只需要简单配置下即可,像这样:

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

tags.jsonattributes.json 需要包含在我们的打包目录中。当前这两个文件的内容,我们也可以看下:

// 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": "属性说明:设置列表项标题展示使用参数,默认值:'name'"
    },
    ...
}

很明显,这两个文件也是需要我们通过脚本生成。和前面提到的一样,这里涉及到组件以及和它们关联的信息,为了能够保持一致并且维护一份,我们这里通过每个组件源码下面的 doc.md 文件来获取。因为,这个文件中包含了组件的 props 以及它们的详细说明和默认值。

组件 props 详细信息

tags, attibutes, componentMap 都需要获取这些信息。 我们首先来看看 doc.md 中都包含什么?

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

| 字段     | 说明                                                             | 类型   | 默认值 |
| -------- | ---------------------------------------------------------------- | ------ | ------ |
| size     | 设置头像的大小,可选值为:large、normal、small,支持直接输入数字   | String | normal |
| shape    | 设置头像的形状,可选值为:square、round            | String | round  |
...

每个组件的 md 文档,我们预览时是通过 vite 提供的插件 vite-plugin-md,来生成对应的 html,而这个插件里面引用到了 markdown-it 这个模块。所以,我们现在想要解析 md 文件,也需要借助于 markdown-it 这个模块提供的 parse API.

// Function getSources
let sources = MarkdownIt.parse(data, {});
// data代表文档内容,sources代表解析出的list列表。这里解析出来的是Token列表。

学新通技术网

Token 中,我们只关心 type 即可。因为我们要的是 props,这部分对应的 Tokentype 就是 table_opentable_close 中间所包含的部分。考虑到一个文档中有多个 table。这里我们始终取第一个,*** 这也是要求我们的开发者在写文档时需要注意的地方 ***。

拿到了中间的部分之后,我们只要在这个基础上再次进行筛选,选出 tr_opentr_close 中间的部分,然后再筛选中间 type = inline 的部分。最后取 Token 这个对象中的 content 字段即可。然后在根据上面三个文件不同的需求做相应的处理即可。

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;
};

1、创建一个基于 vscode 的项目,在它提供的钩子中注册不同行为的 commandlanguages,并实现对应的行为

2、结合 vetur,配置 packages.json

3、针对 map json 文件,需要提供相应的生成脚本,确保信息的一致性。这里解析 md 需要使用 markdown-it 给我们提供的 parse 功能。

最后

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanffgeh
系列文章
更多 icon
同类精品
更多 icon
继续加载