VS Code插件开发,底层对接chatgpt,实现代码优化,真TM不错

451 阅读2分钟

先上效果:

run.gif

完整代码:GITHUB

参考VS Code 插件开发官方文档

本文将介绍如何开发一个 VS Code 插件,以便你可以为自己和其他开发者增强 VS Code 的功能。

1. 准备工作

首先,你需要一个名为 Yeoman 的生成器,它将帮助你创建一个新的 VS Code 插件项目。

2. 创建一个新的 VS Code 插件项目

运行以下命令,安装 Yeoman 生成器:

npm install -g yo generator-code

接下来,运行以下命令创建一个新的插件项目:

yo code

按照提示输入插件名称和描述信息,选择插件类型,并选择是否使用 TypeScript。最后,Yeoman 将为你创建一个新的插件项目,并下载必要的依赖项。

3. 开发插件功能

项目搭建好之后,就可以开发了。插件入口文件就是extension.ts文件。

梳理一下核心逻辑:

  1. 在插件中创建一个webview
  2. webview加载一个在线web站点
  3. 点击“优化代码”将vscode选中的源代码,通过postMessage传递到在线web站点
  4. web站点对接了chatgpt的接口,往chatgpt发送优化代码的指令
  5. web站点得到结果,并展示

下面看看核心部分代码:

在activate方法中注册一个命令code-optimization.doopt,当鼠标右键点击“优化代码”时,触发此命令。


	let doopt = vscode.commands.registerCommand('code-optimization.doopt', () => {
		 
		
		let sourceCode :string | undefined;

		const selection = vscode.window.activeTextEditor?.selection;
		if(selection!==undefined && !selection?.isEmpty){
			 
			const sr = new vscode.Position(selection.start.line,selection.start.character);
			const er = new vscode.Position(selection.end.line,selection.end.character);
			const range = new vscode.Range(sr,er);
			sourceCode = vscode.window.activeTextEditor?.document.getText(range);
		}else{
			sourceCode = vscode.window.activeTextEditor?.document.getText();
		}
		
		if(!sourceCode){
			vscode.window.showInformationMessage('请选中需要优化的代码片段!');
			return 
		}
		
         if(!hasPanel){
			initWebview()
		 }
		 
		 codePanel.webview.postMessage({ 
			type: 'opt' ,
			content:sourceCode
		});
	
	});

接下来,创建一个webview


	function initWebview(){
		hasPanel = true
		codePanel = vscode.window.createWebviewPanel(
			'code-optimization-result', // Identifies the type of the webview. Used internally
			'问天AI助手', // Title of the panel displayed to the user
			vscode.ViewColumn.Two, // Editor column to show the new webview panel in.
			{
				enableScripts:true
			} 
		  );

		  codePanel.onDidDispose(()=>{
			hasPanel=false
		  });
		codePanel.webview.html = getWebContents();
	 
	}

	function getWebContents(){
		return `<!DOCTYPE html>
		<html lang="en">
		
		<head>
		  <meta charset="UTF-8">
		  <meta name="viewport" content="width=device-width, initial-scale=1.0">
		  <title></title>
		  <style>
			html,
			body {
			  height: 100%;
			  overflow-x: hidden;
			}
		  </style>
		</head>
		
		<body>
			 <iframe id="mysite" style="height:100vh;width:100vw" src="https://www.h3d.cc" ></iframe>
		
		  <script>
		
			   const mysite = document.getElementById('mysite')
				
				window.onmessage= (event)=>{
				  const data = event.data;
				  if(!event.origin.includes('vscode-webview')){
					   return
				  }
				  mysite.contentWindow.postMessage(data,"*")
				}
		
		  </script>
		</body>
		
		</html>`
	}

在package.json中配置右键菜单等信息:

"contributes": {
    "commands": [
      {
        "command": "code-optimization.doopt",
        "title": "优化代码"
      },
      {
        "command": "code-optimization.opt",
        "title": "问天AI助手"
      }
    ],
    "menus": {
      "editor/title": [
        {
          "command": "code-optimization.opt",
          "group": "navigation"
        }
      ],
      "editor/context":[
        {
          "command": "code-optimization.doopt",
          "group": "navigation"
        }
      ]
    },
    "keybindings":[
      
      {"key": "alt+8","command": "code-optimization.opt","when": "editorTextFocus"}
    ]
  },

4. 测试插件

在开发插件时,可以使用“Launch Extension”调试配置来启动调试器。通过单击调试按钮,可以在 VS Code 编辑器中启动你的插件,并测试其功能。

5. 发布插件

当你的插件准备好发布时,可以使用“vsce”命令行工具将其发布到 Visual Studio Code Marketplace。首先,你需要在 Visual Studio Code Marketplace 上注册一个账户。接下来,运行以下命令:

npm install -g vsce
vsce login
vsce publish

这将上传你的插件到 Marketplace,并使其在 VS Code 编辑器中可用。

总结

开发一个 VS Code 插件可能需要一些学习和时间,但这是值得的。插件可以为你的工作流程带来许多便利。

另外,本插件已经发到官方市场,可在VSCODE插件市场搜索“问天AI助手”进行体验。