日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

vscode-扩展插件

發布時間:2023/12/10 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 vscode-扩展插件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

title: vscode-擴展插件
categories: VSCode
tags: [vscode, 插件, 擴展]
date: 2018-10-31 14:44:18
comments: false

因為 vscode 已經是我的主用開發工具, 已經拋棄了 sublime text, vs. 開發 unity, shader, lua, h5 等幾乎都是用它了. 很多時候需要偷懶, 就寫個插件輔助一下. ( 工欲善其事必先利其器 )


相關資料

  • https://segmentfault.com/a/1190000009795672
  • 官方文檔 - https://code.visualstudio.com/docs/extensions/example-hello-world
  • 中文文檔 - https://liiked.github.io/VS-Code-Extension-Doc-ZH/#/
  • 官方api - https://code.visualstudio.com/docs/extensionAPI/overview
  • 官方插件示例 - https://github.com/Microsoft/vscode-extension-samples
  • 參考
    • VSCode插件開發急速入門 - http://jdc.jd.com/archives/212586
    • VSCode 插件開發初體驗 - https://www.jianshu.com/p/2ae7668785c7
    • 插件機制詳述 - http://www.ayqy.net/blog/插件機制詳述_vscode插件開發筆記1/
    • 清單文件package.json 說明 - https://jeasonstudio.gitbooks.io/vscode-cn-doc/content/md/擴展API/擴展manifest文件.html

本地插件保存路徑

可以參考 別人 寫插件的方式來寫 自己 的插件.

  • 已有插件所在目錄

    ospath
    windows%USERPROFILE%.vscode\extensions
    macOS~/.vscode/extensions
    Linux~/.vscode/extensions
  • 插件保存文件夾名字規則, [作者名].[插件名].[版本號] , 例如


官方samples

  • 官方插件示例 - https://github.com/Microsoft/vscode-extension-samples

  • 如果運行時報錯. 一下步驟逐步執行測試

  • 安裝相關依賴, 直接在工作區輸入命令: npm install

  • 當前工作區已有 npm watch 任務在運行. 可以在終端 kill. 也可直接切換成別的工作區 再切回來

  • 可能是舊版本未更新, 更新一下

  • package.json 文件中 scripts 字段修改為一下內容

    "scripts": {"vscode:prepublish": "npm run compile","compile": "tsc -p ./","watch": "tsc -watch -p ./","postinstall": "node ./node_modules/vscode/bin/install","test": "npm run compile && node ./node_modules/vscode/bin/test"},
  • tasks.json 文件中

    {"version": "2.0.0","tasks": [{"type": "npm","script": "watch","problemMatcher": "$tsc-watch","isBackground": true,"presentation": {"reveal": "never"}}] }
  • launch.json 文件修改

    {"version": "0.2.0","configurations": [{"name": "Extension","type": "extensionHost","request": "launch","runtimeExecutable": "${execPath}","args": ["--extensionDevelopmentPath=${workspaceFolder}"],"outFiles": ["${workspaceFolder}/out/**/*.js"],"preLaunchTask": "npm: watch"}] }

前置物料

  • 安裝 Yeoman , 命令 : npm install -g yo
  • 安裝 Yeoman 的 generator-code, 命令 : npm install -g generator-code
  • 安裝打包插件的工具 命令 : npm install -g vsce

  • 初始化工程

  • 初始化一個新工程, 命令: yo code . 這里選擇的是 ts extension 工程. 然后照著提示輸入 name, description 等等

    C:\Users\Administrator>yo code_-----_ ╭──────────────────────────╮| | │ Welcome to the Visual │|--(o)--| │ Studio Code Extension │`---------′ │ generator!( _′U`_ ) ╰──────────────────────────╯/___A___\ /| ~ |__'.___.'__′ ` |° ′ Y `? What type of extension do you want to create? New Extension (TypeScript) ? What's the name of your extension? VSC-Plugin001 ? What's the identifier of your extension? wilkeryun ? What's the description of your extension? my custom plugin ? What's your publisher name (more info: https://code.visualstudio.com/docs/tools/vscecli#_publishing-extensions)? yangxuan0261 ? Enable stricter TypeScript checking in 'tsconfig.json'? Yes ? Setup linting using 'tslint'? Yes ? Initialize a git repository? Yescreate wilkeryun\.vscode\launch.json... vscode.d.ts successfully installed!wilkeryun@0.0.1 C:\Users\Administrator\wilkeryun
    • 生成目錄結構

    • package.json : 定義 入口文件, 命令, 顯示在那些地方 (左邊欄, 標題欄 等等), 插件描述等 信息. 基本所有的配置這里


  • 新建一個命令

  • 在 package.json 文件中加入相關配置

    { ..."activationEvents": ["onCommand:extension.sayHello","onCommand:myext.copyLuaFileName" // 3. 激活這個命令],"main": "./out/extension","contributes": {"commands": [{"command": "extension.sayHello","title": "Hello World title"},{ // 1. 新增一個命令 myext.copyLuaFileName"command": "myext.copyLuaFileName","title": "復制lua文件" // 命名顯示名稱}],"menus": {"explorer/context": [{ // 2. 設置這個定義出現在左邊欄"when": "!explorerResourceIsFolder", // 自定義顯示條件, 非文件夾就顯示"command": "myext.copyLuaFileName","group": "navigation"}]}},... }
  • 在 extension.ts 文件中 注冊這個命令及對應的相關自定義邏輯

    export function activate(context: vscode.ExtensionContext) {...let run = vscode.commands.registerCommand("myext.copyLuaFileName", (fileUri) => {vscode.window.showInformationMessage('復制的文件 fileUri:' + fileUri);});context.subscriptions.push(run); }
  • 測試. 按 F5 , 會運行一個 新的vscode進程


  • 打包 使用 插件

    打包

    • 在插件根目錄下使用命令: vsce package , 會在該目錄下生產一個 xxx.vsix 插件文件

      F:\git_repo\wilkeryun>vsce package Executing prepublish script 'npm run vscode:prepublish'... ... A 'repository' field is missing from the 'package.json' manifest file. Do you want to continue? [y/N] y Created: F:\git_repo\wilkeryun\wilkeryun-0.0.1.vsix (7 files, 3.21KB)
      • TODO: 這個報錯暫時未去查
      • 過程中可能會提示你先修改 README.md 文件才能打包,簡單描述功能即可。

    使用

  • 安裝, 手動安裝插件文件

    然后選擇 從 VSIX 安裝…, 選擇 xxx.vsix 文件即可

  • 可以在插件列表中看到這個插件, ctrl + shift + x 顯示插件列表

  • 打包, 發布 參考: http://jdc.jd.com/archives/212586


    發布

    • 參考: https://liiked.github.io/VS-Code-Extension-Doc-ZH/#/extension-authoring/publish-extension , 獲取Personal Access Token (PAT)
  • 創建發布者,

    F:\git_repo\wilkeryun>vsce create-publisher wilker // wilker 這個隨意 Publisher human-friendly name: (wilker) E-mail: wolegequ@live.com // 這個郵箱是微軟的登錄賬號 Personal Access Token: **************************************************** // (PAT)Successfully created publisher 'wilker'.
  • 發布

    F:\git_repo\wilkeryun>vsce publish -p hqg5tqkkjsdasdasdasdadasdasdasdasd //(PAT) Executing prepublish script 'npm run vscode:prepublish'...> wilkeryun@0.0.1 vscode:prepublish F:\git_repo\wilkeryun > npm run compile> wilkeryun@0.0.1 compile F:\git_repo\wilkeryun > tsc -p ./A 'repository' field is missing from the 'package.json' manifest file. Do you want to continue? [y/N] y Publishing yangxuan0261.wilkeryun@0.0.1... Successfully published yangxuan0261.wilkeryun@0.0.1! // 發布成功 Your extension will live at https://marketplace.visualstudio.com/items?itemName=yangxuan0261.wilkeryun (might take a few seconds for it to show up).
    • 然后就可以看到發布結果 (這是改了名稱和版本的截圖)

  • 搜索使用

  • 踩坑

    • 報錯

      Error: Failed Request: Unauthorized(401) - https://marketplace.visualstudio.com/_apis/gallery Be sure to use a Personal Access Token which has access to **all accessible accounts**. See https://code.visualstudio.com/docs/tools/vscecli#_common-questions for more information.

      沒有賦予最高權限


    擴展清單文件 package.json

    每個VS Code擴展需要一個清單文件package.json,該文件位于擴展的根目錄中。

    字段

    名稱是否必要類型說明
    namestring擴展的名稱,該名稱必須為小寫且不能有空格。
    versionstringSemVer 兼容版本.
    publisherstring發布人名字
    enginesobject一個至少包含vscode鍵值對的對象,該鍵表示的是本擴展可兼容的VS Code的版本,其值不能為*。比如 ^0.10.5 表示擴展兼容VS Code的最低版本是0.10.5。
    licensestring參考 npm’s 文檔. 如果你確實需要在擴展根目錄下有一個授權文檔,那么應該把license值設為"SEE LICENSE IN <filename>"。
    displayNamestring用于在擴展市場中本擴展顯示的名字。
    descriptionstring一份簡短的說明,用來說明本插件是什么以及做什么
    categoriesstring[]你希望你的擴展屬于哪一類,只允許使用這幾種值:[Languages, Snippets, Linters, Themes, Debuggers, Other]
    keywordsarray一組 關鍵字 或者 標記,方便在市場中查找。
    galleryBannerobject幫助格式化市場標題以匹配你的圖標,詳情如下。
    previewboolean在市場中把本擴展標記為預覽版本。
    mainstring擴展的入口點。
    contributesobject一個描述擴展 貢獻點的對象。
    activationEventsarray一組用于本擴展的 激活事件。
    dependenciesobject你的擴展所需的任何運行時的Node.js依賴項,和 npm’s dependencies一樣。
    devDependenciesobject你的擴展所需的任何開發的Node.js依賴項. 和 npm’s devDependencies一樣。
    extensionDependenciesarray一組本擴展所需的其他擴展的ID值。擴展的ID值始終是 ${publisher}.${name}。比如:vscode.csharp。
    scriptsobject和 npm’s scripts一樣,但還有一些額外VS Code特定字段.
    iconstring一個128x128像素圖標的路徑。

    也可以查看npm’s package.json參考文檔.

    范例

    這里有一個完整的package.json:

    {"name": "Spell","displayName": "Spelling and Grammar Checker","description": "Detect mistakes as you type and suggest fixes - great for Markdown.","icon": "images/spellIcon.svg","version": "0.0.19","publisher": "seanmcbreen","galleryBanner": {"color": "#0000FF","theme": "dark"},"license": "SEE LICENSE IN LICENSE.md","bugs": {"url": "https://github.com/Microsoft/vscode-spell-check/issues","email": "smcbreen@microsoft.com"},"homepage": "https://github.com/Microsoft/vscode-spell-check/blob/master/README.md","repository": {"type": "git","url": "https://github.com/Microsoft/vscode-spell-check.git"},"categories": ["Linters", "Languages", "Other"],"engines": {"vscode": "0.10.x"},"main": "./out/extension","activationEvents": ["onLanguage:markdown"],"contributes": {"commands": [{"command": "Spell.suggestFix","title": "Spell Checker Suggestions"}],"keybindings": [{"command": "Spell.suggestFix","key": "Alt+."}]},"scripts": {"vscode:prepublish": "node ./node_modules/vscode/bin/compile","compile": "node ./node_modules/vscode/bin/compile -watch -p ./"},"dependencies": {"teacher": "^0.0.1"},"devDependencies": {"vscode": "^0.11.x"} }


    相關api

    關于 contributes.configuration

    參考: https://code.visualstudio.com/docs/extensionAPI/extension-points#_contributesconfiguration


    關于 contributes.commands

    參考: https://code.visualstudio.com/docs/extensionAPI/extension-points#_contributescommands


    關于 contributes.menus

    參考: https://code.visualstudio.com/docs/extensionAPI/extension-points#_contributesmenus


    踩坑

    • 在 左邊欄 或 這編輯區 右鍵時, 可以辦當前文件 uri 傳進去的, 但是如果將這個 命令 注冊為快捷鍵, 使用快捷鍵時是無法獲取到這個uri的, 為 null

      let run = vscode.commands.registerCommand("myext.copyLuaFileName", (fileUri) => {console.log("--- fileUri 111:", fileUri);});

      但是可以通過api獲取到當前激活的文檔, 從而獲取到 fileUri

      if (fileUri === undefined) {fileUri = vscode.window.activeTextEditor!.document.uri; }
    • 目前還不支持 vscode.window.showInformationMessage 提示框的關閉, 必須手動關閉

      參考 - https://stackoverflow.com/questions/34893733/how-to-programmatically-close-vscode-windows-showinformationmessage-box

      但是支持在 底部狀態欄 中顯示信息, 并設置自動關閉時間. vscode.window.setStatusBarMessage


    關于 when

    • 在顯示在相關菜單時有個條件 (when) 可以讓其判斷是否顯示.

      "contributes": {"menus": {"editor/context": [{"when": "config.wilker-cfg.showLuaCopy && editorLangId == lua && !inOutput", // 在 configuration 中定義這個配置, 必須是 bool 值"command": "wilker-ext.copyLuaFileName","group": "myGroup@110"}]},"configuration": {"type": "object","title": "Wilker Plugin Configuration","properties": {"wilker-cfg.showLuaCopy": { // 這個值可以暴露給用戶設置在 全局 或 工作區"type": "boolean","default": false,"description": "是否顯示 復制lua 在右鍵菜單中","scope": "resource"}}} }
    • 這樣是 配死 定義, 不能動態變化 根據文件是否是某些特定文件 才讓其 是否顯示在 右鍵 中. 有個方法可以動態修改這個值, 不過應該是有點消耗性能的, 就是注冊一個 切換編輯文件回調, 動態修改 配置值

      vscode.window.onDidChangeActiveTextEditor((e) => {// 判斷條件let isShow = true;let cfg = vscode.workspace.getConfiguration("wilker-cfg");cfg.update("showLuaCopy", isShow, vscode.ConfigurationTarget.Workspace); });
    • ps: 這是曲線救國的方式, 不知道正確的姿勢是怎么樣. 局限性是只能在 切換編輯文件 時能觸發到

    內置when條件
    • 參考 vscode 源碼, 所屬關鍵字 new RawContextKey<boolean>( , 看到的都是可用內置條件
    使用正則表達式
    • 格式: sameName =~ /正則表達式/

      {"when": "editorLangId =~ /(lua|csharp)/", // 表示只有文件是 lua或者csharp 時, 條件才為 true... },
      • 注意中間的符號是 =~, 如果使用的是 == 則為普通的判斷
    • 參考: https://github.com/Microsoft/vscode/issues/26044


    關于 activate deactivate

    這兩個函數都在入口文件 extension.ts 中

    activate

    這個函數的調用時機可以根據需要配置.

    "activationEvents": ["onCommand:wilker-ext.copyLuaFileName" // 調用這個命令是才調用 activate],"activationEvents": ["*" // 已啟動vscode 調用 activate],

    參考 Activation Events - package.json - https://code.visualstudio.com/docs/extensionAPI/activation-events

    deactivate

    關閉vscode時會觸發, 如果有異步的必須返回 Promise. Extension must return a Promise fromdeactivate()if the cleanup process is asynchronous

    export function deactivate() {return new Promise<boolean>(async (resolve, reject) => {await mycleanfunc();resolve();}); }

    關于 TextDocument.languageId

    切換編輯文件時可用于一些邏輯判斷

    參考 Language Identifiers - https://code.visualstudio.com/docs/languages/identifiers


    顯示命令的各種地方

    配置在 package.json

    {"contributes": {"menus": { // 配置在這個字段中"explorer/context": [{"when": "!explorerResourceIsFolder","command": "myext.copyLuaFileName","group": "navigation"}]...}},}


    左邊欄 右鍵

    key : "explorer/context"

    編輯區 右鍵

    key: "editor/context"

    總結

    以上是生活随笔為你收集整理的vscode-扩展插件的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。