程序员Web前端之路Visual Studio Code

visual studio code 扩展进阶(1)

2019-06-17  本文已影响17人  zidea
vscode

一切重想法开始,我们都是从一个想象走向一个实现。

  1. 使用 yeoman 创建项目脚手架
  2. 创建个人的 VS 在线账号
  3. 发布自己的

an average individual that likes the program and as we are as we all
最近许多 csharp 工程师转型为 javascript

扩展目录结构

目录结构

package.json 是整个项目配置,也可以提供对项目描述和说明
tsconfig.json 配置以何种方式来对 typescript 文件进行编译
tslint.json 对 ts 语法问题给予开发者友好提示
CHANGELOG.MD 包好 extension 更改的日志信息
.vscode\launch.json 配置启动扩展的方式
src\extension.js 扩展程序的代码
test 测试目录

在项目中默认的测试工具为 Mocha 测试框架,今天可能会用到比较熟悉的 jest 测试框架

cnpm install -D jest ts-test @types/jest
import * as path from "path";
import * as fs from "fs";

import { InputBoxOptions } from "vscode";
import { IDisposable } from "./disposable.interface";
import { ScExistError } from "./errors/sc-exist.error";
import { VSCodeWindow } from "./vscode.interfaces";

export class ScGenerator implements IDisposable {
  private readonly extension = ".js";

  private readonly scFiles = [
    "operators",
    "selectors",
    "actions",
    "reducers",
    "types",
    "test",
    "index"
  ];

  private readonly defaultPath = "src/state/sc";

  constructor() {}

  async execute(): Promise<void> {}
  async prompt(): Promise<string | undefined> {}
  create(absSCPath: string) {}
  validate(name: string): string | null {}
  toAbsolutePath(name: string): string {}

  dispose() {}
}

可能看到文件内容有点 confusing,我们先不管其他内容,只是关注我们关心的内容,

构造函数

在构造函数中我们定义两个参数分别是

  constructor(
    private workspaceRoot:string,
    private window:VSCodeWindow
  ) {
      
  }

使用下面接口好处是我们并不想使用 vscode sdk,所以抽象出一个接口将我们想要用的方法整合到这里。

vscode.interfaces.ts 文件
import { InputBoxOptions } from "vscode";
export interface VSCodeWindow {
  showErrorMessage(message: string): Thenable<string>;
  showInfomationMesssage(message: string): Thenable<string>;
  showInputBox(options?: InputBoxOptions): Thenable<string | undefined>;
}

toAbsolutePath 方法

将相对路径转换为绝对路径,如果是文件则使用默认路径放置文件

toAbsolutePath(nameOrRelativePath: string): string {
    //检查参数中是否包含 / 或 ./
    if (/\/|\\/.test(nameOrRelativePath)) {
      return path.resolve(this.workspaceRoot, nameOrRelativePath);
    }

    // 如果是文件则使用默认路径
    //
    return path.resolve(
      this.workspaceRoot,
      this.defaultPath,
      nameOrRelativePath
    );
  }
对输入名称是否正确进行检查
  validate(name: string): string | null {
    if (!name) {
      return "Name is required";
    }

    if (name.includes(" ")) {
      return "Space are not allowed";
    }

    return null;
  }
  async prompt(): Promise<string | undefined> {
    const options: InputBoxOptions = {
      ignoreFocusOut: true,
      placeHolder: "quack",
      validateInput: this.validate,
      prompt: `Sc name: 'some_sc , or relative path:'src/state/sc/some_sc'`
    };

    return await this.window.showInputBox(options);
  }
上一篇 下一篇

猜你喜欢

热点阅读