其他分享
首页 > 其他分享> > vscode插件编写,翻译英文和将中文改为驼峰英文

vscode插件编写,翻译英文和将中文改为驼峰英文

作者:互联网

1、安装 yo 和 generator-code

 yarn global add yo generator-code

2、执行 yo code 生成插件脚手架

yo code

 

 配置项说明:

选择插件类型
* ? What type of extension do you want to create? New Extension (TypeScript)

设置插件名字
* ? What's the name of your extension? HelloWorld

插件标识,可选择默认
* ? What's the identifier of your extension? helloworld

插件描述,可选择默认
* ? What's the description of your extension? LEAVE BLANK

是否初始化一个 git 仓库地址,可选择默认
* ? Initialize a git repository? Yes

选择包管理器,可选择默认
* ? Which package manager to use? npm

3、使用vscode打开该项目并安装相应的依赖,按 F5 启动项目,将会进行编译,并启动一个新的 vscode 插件开发主机窗口,执行命令一般为项目名称.helloWorld

在vscode中,同时按下 ctrl + shift + p 调出命令控制面板

输入 hello 找到 命令 my-vscode-plugin.helloWorld

执行输出:

此时初始案例测试成功

 

4、对插件进行修改

主要修改extension.js主文件,如下代码修改

const vscode = require("vscode");
const axios = require("axios");
const qs = require("qs");

async function youdaoTranslate(text) {
  var args = {
    keyfrom: "YouDaoCV",
    key: "659600698",
    type: "data",
    doctype: "json",
    version: "1.1",
    q: text,
  };

  return new Promise((resolve, reject) => {
    var url = "http://fanyi.youdao.com/openapi.do";
    axios
      .post(url, qs.stringify(args), {})
      .then((res) => {
        try {
          resolve(res.data.translation[0]);
        } catch (error) {
          resolve("单词未找到释义");
        }
      })
      .catch((err) => {
        console.log(err);
        reject(err.data);
      });
  });
}

//缓存
let Cache = [];
let translate = "";
/**
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {
  console.log('Congratulations, your extension "ztrans" is now active!');
  let disposable = vscode.commands.registerCommand(
    "ztrans.translate",
    async () => {
      const { activeTextEditor } = vscode.window; //获取当前聚焦的文本编辑器
      const currentSelect = activeTextEditor.document.getText(
        activeTextEditor.selection
      ); //根据范围选取文本
      let result = await youdaoTranslate(currentSelect);
      //转换驼峰
      result = result
        .split(" ")
        .map((v, i) => {
          return i !== 0
            ? v.charAt(0).toLocaleUpperCase() + v.slice(1).toLocaleLowerCase()
            : v.toLocaleLowerCase();
        })
        .join("")
        .replace(/[.,;':]/g, "");
      activeTextEditor.edit((editBuilder) => {
        editBuilder.replace(activeTextEditor.selection, result); //将翻译内容替换
      });
    }
  );
  //悬浮翻译
  vscode.languages.registerHoverProvider("*", {
    provideHover: async (document, position) => {
      const word = document.getText(document.getWordRangeAtPosition(position)); //获取悬浮区域文本
      if (word in Cache) {
        translate = Cache[word]; //读取缓存的翻译
      } else {
        translate = await youdaoTranslate(word);
        Cache[word] = "[cache] " + translate;
      }
      return new vscode.Hover("中文翻译: " + translate);
    },
  });
  context.subscriptions.push(disposable);
}

// this method is called when your extension is deactivated
function deactivate() {}

module.exports = {
  activate,
  deactivate,
};

命令 my-vscode-plugin.helloWorld改成了ztrans.translate,并对功能进行了实现,悬浮时显示翻译,选择需要转化的中文可以转化为驼峰英语,方便命名

 

5、打包(不做发布流程)

1、 全局安装 vsce

VS Code 插件使用 vsce 来进行管理,如打包、发布等

yarn global add vsce

2、打包插件

vsce package
生成一个.vsic文件,可以在vscode中直接安装

3、项目地址:https://gitee.com/LiJun3486/ztrans-main

 

标签:插件,const,extension,vscode,英文,word,translate
来源: https://www.cnblogs.com/lijun12138/p/16383892.html