返回
用插件强力优化你的 VSCode 开发体验
前端
2023-09-30 06:58:50
工欲善其事,必先利其器。VSCode 作为优秀的开发工具,给我的日常开发工作提供了极大的便利。其拓展机制更是如此。
但是,最近在做年度专业线任务时,有需要用到漂亮的行尾注释对齐,搜索后发现 vscode 官方插件市场没有我想要的。于是便想着自己来开发这么个东西,一方面方便后边自己使用,另一方面也可以增加自己的知识面。
插件开发实践
1. 创建项目
首先,我们需要创建一个新的 VSCode 扩展项目。我们可以使用 Yeoman 来轻松完成这一步。
npm install -g yo
yo code
这将在当前目录下创建一个新的扩展项目。
2. 实现插件功能
接下来,我们需要实现插件的功能。我们将创建一个名为 "Align Comments" 的插件。
// extension.ts
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
let disposable = vscode.commands.registerCommand('extension.alignComments', () => {
// Get the current editor
const editor = vscode.window.activeTextEditor;
// If there is no active editor, return
if (!editor) {
return;
}
// Get the current selection
const selection = editor.selection;
// Get the text of the selected lines
const lines = editor.document.getText(selection).split('\n');
// Find the longest comment in the selected lines
let longestCommentLength = 0;
for (const line of lines) {
const commentIndex = line.indexOf('//');
if (commentIndex > -1) {
const commentLength = line.length - commentIndex;
if (commentLength > longestCommentLength) {
longestCommentLength = commentLength;
}
}
}
// Pad the comments to the longest comment length
for (const line of lines) {
const commentIndex = line.indexOf('//');
if (commentIndex > -1) {
const comment = line.substring(commentIndex);
const padding = ' '.repeat(longestCommentLength - comment.length);
editor.edit((editBuilder) => {
editBuilder.insert(new vscode.Position(selection.start.line, commentIndex), padding);
});
}
}
});
context.subscriptions.push(disposable);
}
export function deactivate() {}
3. 测试插件
现在我们可以测试插件了。
npm run compile
npm install -g vsix
vsix install -i ./extension.vsix
4. 发布插件
如果我们对插件的功能满意,就可以发布它了。
npm run package
vsix publish
Demo 源码
该插件的 demo 源码可以在 GitHub 上找到:
https://github.com/YourUsername/align-comments
结语
希望这篇文章能帮助您开发出自己的 VSCode 插件。如果您有任何问题,请随时在评论区留言。