Skip to content

vscode开发 #46

Description

@Wscats

安装code命令

打开VSC快捷键⇧⌘P打开命令行找到shell command选择Shell Command: Install 'code' command in PATH command安装

屏幕快照 2019-04-29 下午5 31 59

安装脚手架

执行完以下命令后,在VSC按F5,此时成功的话会打开一个新的调试窗口(扩展开发主机)

npm install -g yo generator-code
yo code
# ? 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
code ./helloworld

Hello World

快捷键⇧⌘P打开命令行,执行Hello World

屏幕快照 2019-04-29 下午5 29 23

添加右键菜单和快捷键

打开package.json,按照下述方式添加:

extension.sayHello对应的是extension.js里面的方法

{"contributes": {"commands": [{"command": "extension.sayHello","title": "Hello World"}],// 快捷键绑定"keybindings": [{"command": "extension.sayHello","key": "ctrl+f10","mac": "cmd+f10","when": "editorTextFocus"}],// 设置菜单"menus": {"editor/context": [{"when": "editorFocus","command": "extension.sayHello","group": "navigation"}]}}}

setting.json

Code->首选项设置->设置->文本编辑器->文件->Associations

{
"git.ignoreMissingGitWarning": true,
"explorer.confirmDelete": false,
"javascript.updateImportsOnFileMove.enabled": "never",
"files.associations": {
"*.cjson": "jsonc",
"*.wxss": "css",
"*.wxs": "javascript",
"*.omi": "html"
}
}

打包 发布

无论是本地打包还是发布到应用市场都需要借助vsce这个工具

npm i vsce -g

打包成vsix文件

vsce package

登录marketplacejian上传

监听命令

varvscode=require('vscode');functionactivate(context){// when you click ctrl+s, fn will actionvscode.workspace.onDidSaveTextDocument(function(document){console.log(document)});}exports.activate=activate;

Webview

读取html需要vscode-resource配合

// The module 'vscode' contains the VS Code extensibility API// Import the module and reference it with the alias vscode in your code belowimport*asvscodefrom'vscode';import*aspathfrom'path';import*asfsfrom'fs';/** * 从某个HTML文件读取能被Webview加载的HTML内容 * @param {*} context 上下文 * @param {*} templatePath 相对于插件根目录的html文件相对路径 */functiongetWebViewContent(context: vscode.ExtensionContext,templatePath: string){constresourcePath=path.join(context.extensionPath,templatePath);constdirPath=path.dirname(resourcePath);lethtml=fs.readFileSync(resourcePath,'utf-8');// vscode不支持直接加载本地资源,需要替换成其专有路径格式,这里只是简单的将样式和JS的路径替换html=html.replace(/(<link.+?href="|<script.+?src="|<img.+?src=")(.+?)"/g,(m,$1,$2)=>{return$1+vscode.Uri.file(path.resolve(dirPath,$2)).with({scheme: 'vscode-resource'}).toString()+'"';});returnhtml;}// this method is called when your extension is activated// your extension is activated the very first time the command is executedexportfunctionactivate(context: vscode.ExtensionContext){// Use the console to output diagnostic information (console.log) and errors (console.error)// This line of code will only be executed once when your extension is activatedconsole.log('Congratulations, your extension "qf" is now active!');// The command has been defined in the package.json file// Now provide the implementation of the command with registerCommand// The commandId parameter must match the command field in package.json// 欢迎提示letdisposable=vscode.commands.registerCommand('extension.qf',function(){// vscode.window.showInformationMessage('Hello World');constpanel=vscode.window.createWebviewPanel('testWelcome',// viewType"Welcome to Eno Snippets",// 视图标题vscode.ViewColumn.One,// 显示在编辑器的哪个部位{enableScripts: true,// 启用JS,默认禁用retainContextWhenHidden: true,// webview被隐藏时保持状态,避免被重置});panel.webview.html=getWebViewContent(context,'src/html/index.html');});context.subscriptions.push(disposable);// 如果设置里面开启了欢迎页显示,启动欢迎页constkey='vscodePluginDemo.showTip';if(vscode.workspace.getConfiguration().get(key)){vscode.commands.executeCommand('extension.qf');}}// this method is called when your extension is deactivatedexportfunctiondeactivate(){}

配置参数

package.json配置文件如下:

"configuration": {"title": "Px to rem configuration","properties": {"px-to-rem.px-per-rem": {"type": "integer","default": 16,"description": "Number of pixels per 1rem."},"px-to-rem.only-change-first-ocurrence": {"type": "boolean","default": false,"description": "Set value to only change first occurence of px/rem per selection."},"px-to-rem.notify-if-no-changes": {"type": "boolean","default": true,"description": "Show a warning if no conversion could be made."},"px-to-rem.number-of-decimals-digits": {"type": "integer","default": 4,"description": "Maximum number of decimals digits a px or rem can have."}}}

在代码中获取默认的配置参数

const config = vscode.workspace.getConfiguration("px-to-rem");

FileSystemWatcher

用于监听文件是否发生了变化,可以监听到新建、更新、删除这 3 种事件,也可以选择忽略其中某个类型事件。创建watcher是利用vscode.workspace.createFileSystemWatcher: function createFileSystemWatcher(globPattern: GlobPattern, ignoreCreateEvents?: boolean, ignoreChangeEvents?: boolean, ignoreDeleteEvents?: boolean): FileSystemWatcher;

例如监听所有js文件的变动:

constwatcher=vscode.workspace.createFileSystemWatcher('*.js',false,false,false);watcher.onDidChange(e=>{// 文件发生更新console.log('js changed,'e.fsPath);});watcher.onDidCreate(e=>{// 新建了js文件console.log('js created,'e.fsPath);});watcher.onDidDelete(e=>{// 删除了js文件console.log('js deleted,'e.fsPath);});

设置并持久保存token

https://gitee.com/g8up/vscode-gitee/blob/dev/src/tokens.ts

import{Memento}from'vscode';interfaceTokens{[host: string]: {
token: string;};}exportfunctionsetToken(memento: Memento,provider: string,token: string): void{if(token){consttokens=getToken(memento);tokens[provider]={
token,};memento.update('tokens',tokens);}};exportfunctiongetToken(memento: Memento): Tokens{returnmemento.get<Tokens>('tokens',{});}
export functionremoveToken(memento: Memento,provider: string): void{consttokens: Tokens|undefined=memento.get('tokens');if(tokens){deletetokens[provider];memento.update('tokens',tokens);}}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions