前言
vscode 插件提供了很强大个能力,借助插件可以帮助我们提升开发效率。
在写 node 项目时经常需要相对路径寻找引用 Service 文件等,写一个插件帮我们自动补全。
借助 vscode.languages.registerCompletionItemProvider
方法,我们可以注册相关补全提示。
注册服务
1 2 3 4 5 6 7
| export function activate(context: vscode.ExtensionContext) { context.subscriptions.push( vscode.languages.registerCompletionItemProvider("typescript", { provideCompletionItems, }) ); }
|
provideCompletionItems
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| const provideCompletionItems = async ( document: vscode.TextDocument, position: vscode.Position ) => { const serviceFiles = await vscode.workspace.findFiles("app/services/**/*.ts");
if (!serviceFiles.length) { return; }
return serviceFiles.map((file) => { const relativePath = path.relative( path.dirname(document.uri.path), path.dirname(file.path) );
const basename = path.basename(file.path); const extname = path.extname(file.path); const filename = basename.replace(extname, ""); const insertText = `import ${filename} from '${relativePath}/${filename}';\n${filename}`;
const completionItem = new vscode.CompletionItem( filename, vscode.CompletionItemKind.Class );
completionItem.detail = basename; completionItem.insertText = insertText; completionItem.documentation = `${insertText}`;
return completionItem; }); };
|
配置
同时我们需要在 package.json 中添加相应配置
1 2 3 4 5
| { "activationEvents": [ "onLanguage:typescript" ], }
|
参考