VSCode插件之實時字數統計與選中詞英漢互譯

VSCode插件之字數統計、翻譯

demonstration-gif


hello world 初體驗

環境條件:

  • npm
  • git
  • 最新版的VS Code(我的是1.32.3,結果測試的時候說我版本太低,就升級到了1.33.0)

根據官網給的鏈接your-first-extension, 我們需要安裝一個代碼生成工具,減少重複代碼的編寫。

npm install -g yo generator-code

萬事俱備只欠東風,接下來試試官網的hello world,首先是把項目結構搭建出來。

yo code

根據提示,輸入自己想做的插件名稱,identifier,描述等信息

# ? What type of extension do you want to create? New Extension (TypeScript)
# ? What's the name of your extension? HelloWorld
### Press <Enter> to choose default for all options below ###

# ? What's the identifier of your extension? helloworld
# ? What's the description of your extension? LEAVE BLANK
# ? Enable stricter TypeScript checking in 'tsconfig.json'? Yes
# ? Setup linting using 'tslint'? Yes
# ? Initialize a git repository? Yes
# ? Which package manager to use? npm

然後進入到**./helloworld** 目錄,就可以看到目錄結構已經出來了。這種級別的 demo 一般都是可以直接跑的。

  • 將**./helloworld**目錄放到VS Code中。
  • F5 就會自動進行編譯,然後會打開一個Extension Development Host窗口
  • Command+Shift+P 輸入Hello World就可以看到效果了。

自帶的特效是輸出一個“Hello World” 的**InformationMessage**框。具體可以看:
hello-world-demonstration

經過對Hello World的練手,環境搭建,項目目錄的搭建基本上就熟悉了,然後就可以着手準備本次的插件開發了。

cd ../ && rm -rf helloworld/

目標功能:實時字數統計 + 翻譯選中文本

有些東西不適合從零開始,因爲太浪費時間了,不如找點現成的,站在別人的肩膀上迭代。

實時字數統計

所以我打開VS Code 直接在插件市場輸入word count,結果出來了一堆,然後找了一個看起來還不賴的,ycjc868-vscode-word-count, 點進去Repository地址,先看看人家是怎麼實現的,感覺可用的關鍵代碼有這麼幾個:

// VSCode 底部狀態欄
    private _statusBarItem: vscode.StatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
// 註冊光標改變事件
    vscode.window.onDidChangeTextEditorSelection(this.updateWordCount, this, subscriptions);

// 獲取當前編輯器對象
    const editor = vscode.window.activeTextEditor;
// 獲取文本以及將內容展示到狀態欄
    const wordCount = this._getWordCount(doc);
    this._statusBarItem.text = `${wordCount} Words`;
    this._statusBarItem.show();

翻譯選中的文本

功能已經完成一半了,接下來是實現第二個功能翻譯選中文本,之前寫過一個系統級別的翻譯的工具,基本原理是:

監聽系統剪切板的內容變化,
調用翻譯API完成翻譯任務,
調用系統GUI組件彈出翻譯內容。

能用是能用,就是不太受控制,用的時候開啓服務,不用的時候得關掉,要不然瘋了一樣往外彈提醒。

本次要做一個VS Code中的翻譯,這個場景就蠻適合,最起碼不會打擾到自己。思路還是看看別人是咋實現類似的功能的。找到了一個**天氣預報**的插件,裏面有一段代碼如下:

const config = vscode.workspace.getConfiguration('remind-me') //獲取可配置項中的數據
const appkey = config.hefengAppkey? config.hefengAppkey: 'YOUR_KEY' // 這裏放和風天氣的KEY
WebRequest.get(`https://way.jd.com/he/freeweather?city=${encodeURI(cityName)}&appkey=${appkey}`).
           then(reps => {
               let rep = JSON.parse(reps.body)
               ...... 
           )

我不會TypeScript,所以使用WebRequest的時候,提示我沒有這個類,猜想是需要引入這種腳手架的庫,然後搜了一下,找到一個**Web-Request的使用介紹**。

npm install web-request

然後在**extension.ts**中像引入vscode一樣引用一下。

import * as vscode from 'vscode';
import * as WebRequest from 'web-request';

有道翻譯的API不讓免費用了,那就用百度的翻譯API(翻譯的效果好像也還湊活),鍋碗瓢盆都準備好了,現在該淘米了,那就得拿到選中的文本,代碼如下:

let selection = editor.selection
let text = editor.document.getText(selection)

經過測試發現,代碼是間歇性正常,然後我使用**console.log** 打印了下web請求的結果,發現是返回內容解析出錯了,猜想是漢字在URL中有編解碼的影響,然後會導致出問題。就拿encodeURI對選中的文本加了下處理。

public _translate(keyword: string): string {
    // 獲取選中的文本
    let wcconfig = vscode.workspace.getConfiguration("wordcount");
    let url = wcconfig.transapi ? wcconfig.transapi : "https://fanyi.baidu.com/transapi?from=auto&to=auto&query="
    if(keyword) {
        url = url + encodeURI(keyword)
        WebRequest.get(url).then(resp => {
            let rep = JSON.parse(resp.content);
            console.log(resp.content);
            let transret = rep.data[0].dst;
            this._statusBarItem.text = "[" + keyword + "]:" + transret;
            this._statusBarItem.show();
        });
    }
    return "失敗了~~~~(>_<)~~~~"
}

這樣就可以正常工作了,但是看到剛纔的那個作者的repository中有對於配置文件的使用,爲了減少硬編碼,咱也試試唄。在**package.json**中加入下面的配置項。

"commands": [
    {
        "command": "extension.wordCount",
        "title": "count Words"
    }
],
"configuration":{
    "type": "object",
    "title": "some configuration for translate",
    "properties": {
        "wordcount.transapi": {
            "type": "string",
            "default": "https://fanyi.baidu.com/transapi?from=auto&to=auto&query=",
            "description": "auto translate api from baidu"
        }
    }
},

拓展代碼使用let wcconfig = vscode.workspace.getConfiguration("wordcount");就可以拿到對應的配置值了。

打包、發佈

東西做出來,肯定得分享,不然不會有進步的。然後還是看看別人怎麼弄的,跟着做就好了。找到了一個VSCode插件開發全攻略(十)打包、發佈、升級 真的是詳細。

這裏我說下我遇到的幾個問題。

README.md 文件修改問題

➜  wordcount git:(master) ✗ vsce package
Executing prepublish script 'npm run vscode:prepublish'...

> [email protected] vscode:prepublish /Users/biao/Code/vscode/wordcount
> npm run compile


> [email protected] compile /Users/biao/Code/vscode/wordcount
> tsc -p ./

 ERROR  Make sure to edit the README.md file before you publish your extension.

解決方法:刪掉開頭自動生成的文本,寫點自己的內容就好了。

無法打包

➜  wordcount git:(master) ✗ vsce package
 ERROR  Missing publisher name. Learn more: https://code.visualstudio.com/api/working-with-extensions/publishing-extension#publishing-extensions

解決思路:missing publisher namepackage.json 中加入publisher信息就好了。

倉庫缺失問題

➜  wordcount git:(master) ✗ vsce package
Executing prepublish script 'npm run vscode:prepublish'...

> [email protected] vscode:prepublish /Users/biao/Code/vscode/wordcount
> npm run compile


> [email protected] compile /Users/biao/Code/vscode/wordcount
> tsc -p ./

 WARNING  A 'repository' field is missing from the 'package.json' manifest file.
Do you want to continue? [y/N] n

可以看出這裏是Warning,所以沒有也沒關係。如果想上傳到GitHub上,開頭環境中的git就派上了用場。

git add .
git commit -m 'xxxxxx'
git remote add origin your-git-repository
git push origin master

publish 失敗

➜  wordcount git:(master) ✗ vsce puhlish
Usage: vsce [options] [command]

Options:
  -V, --version                        output the version number
  -h, --help                           output usage information

Commands:
  ls [options]                         Lists all the files that will be published
  package [options]                    Packages an extension
  publish [options] [<version>]        Publishes an extension
  unpublish [options] [<extensionid>]  Unpublishes an extension. Example extension id: microsoft.csharp.
  list <publisher>                     Lists all extensions published by the given publisher
  ls-publishers                        List all known publishers
  create-publisher <publisher>         Creates a new publisher
  delete-publisher <publisher>         Deletes a publisher
  login <publisher>                    Add a publisher to the known publishers list
  logout <publisher>                   Remove a publisher from the known publishers list
  show [options] <extensionid>         Show extension metadata
  search [options] <text>              search extension gallery
  *

跟教程上的不一樣,怎麼就是不成功。後來想了下發布肯定是要身份信息的,照應剛纔的Token信息。所以先將publisher登陸下。

➜  wordcount git:(master) ✗ vsce login guoruibiao
Publisher 'guoruibiao' is already known
Do you want to overwrite its PAT? [y/N] y
Personal Access Token for publisher 'guoruibiao': ****************************************************

(node:95091) Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.
➜  wordcount git:(master) ✗ vsce publish
Executing prepublish script 'npm run vscode:prepublish'...

> [email protected] vscode:prepublish /Users/biao/Code/vscode/wordcount
> npm run compile


> [email protected] compile /Users/biao/Code/vscode/wordcount
> tsc -p ./

This extension consists of 566 separate files. For performance reasons, you should bundle your extension: https://aka.ms/vscode-bundle-extension
Publishing [email protected]...
(node:95103) Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.
 DONE  Published [email protected]
Your extension will live at https://marketplace.visualstudio.com/items?itemName=guoruibiao.wordcount (might take a few seconds for it to show up).

Token 的生成按照剛纔的鏈接跟着做就好了,publish通過後會返回一個地址:

https://marketplace.visualstudio.com/items?itemName=guoruibiao.wordcount

大概5分鐘後就可以訪問了。

分發與安裝

VS Code 插件市場搜索**word count** 找到作者是guoruibiao的那個,點擊**install**,完事。
plugin-market

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章