preface
Vscode is a popular code editor with a powerful yet simple extension development API that allows developers to deeply customize their development environment.
Starting from a real case, this article demonstrates how to complete the development of a vscode extension in 10 minutes and finally put it on the shelf.
Demand background
In daily work, we often need to send a piece of text to the phone, or need to open a web url on the phone.
The usual practice is to use wechat /QQ and other multi-terminal synchronization tools.
If you can directly convert the selected text or URL into a QR code without leaving the editor, and then scan it with your phone to get it, is it much more convenient?
The preparatory work
Once the requirements are identified, you are ready to begin development.
However, before you begin please read again the official development documentation: code.visualstudio.com/api
Vscode provides a wealth of API open capabilities, including:
- Register commands, shortcut keys, context menus
- Stores workspace or global data
- The notification popover and progress bar are displayed
- Use the input prompt box to get user input
- Open the file selector provided by the system
- And so on…
Extension development
The scaffold
First, install the vscode extension development scaffolding:
npm install -g yo generator-code
Copy the code
Next, use YO to complete the basic information configuration of the project as prompted and automatically generate the extension framework:
$ yo code_ -- -- -- -- -- _ ╭ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ | | │ Welcome to the Visual │ | - (o) - | │ Studio Code Extension │ ` -- -- -- -- -- -- -- -- -- ´ │ generator! │ (_ ´ U ` _) ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯ / ___A___ \ | to | __ '. ___. '__ ´ ` | ° ´ ` Y? What type of extension do you want to create? New Extension (JavaScript) ? What's the name of your extension? text2qrcode ? What's the identifier of your extension? text2qrcode ? What's the description of your extension? A vscode extension generates qrcode from text ? Enable JavaScript type checking in 'jsconfig.json'? Yes ? Initialize a git repository? No ? Which package manager to use? npm ......Copy the code
At this point, our basic vsCode extension framework is generated. The directory structure is as follows:
For example, for example, for example, for example, for example, for example, for example, for example, for example, for example, for example, for example, for example, for example, for example, for example, for example, for example, for example, for example, for example, for example Package. json ├── Test ├── vSC-extension - QuickstartCopy the code
Configuration and Dependencies
Next, modify package.json:
{
"name": "text2qrcode"."displayName": "Text2QRCode"."description": "generate qrcode from text"."version": "1.0.0"."publisher": "Ceelog", // Publisher ID"engines": {
"vscode": "^ 1.30.0"
},
"icon": "text2qrcode.png", // Extend the icon"keywords": [...]. ."categories": [
"Other"]."repository": {
"type": "git"."url": "https://github.com/Ceelog/text2qrcode.git"// Extend Git repository address},..."activationEvents": [
"onCommand:extension.text2qrcode"// Note that the name of the command is the same as in the extension code."main": "./extension.js"."contributes": {
"commands": [{"command": "extension.text2qrcode", // Use extensions by command"title": "Text2QRCode"}]."menus": {
"editor/context": [{"command": "extension.text2qrcode", // Use the extension through the menu"title": "Text2QRCode"}]}}..."devDependencies": {... },"dependencies": {
"q": "^ 1.4.1." "."qrcode": "^ 1.4.4." "// Extend dependencies that need to be used}}Copy the code
We based on the framework of automatic generation and increase the publisher icon repository contributes. Menus and extend dependencies, modified activationEvents. OnCommand command names.
Because of the new dependency, you need to complete the dependency installation: NPM install
Extension code
Our extension is simple:
Select text -> Right click generate QR code -> Show QR codeCopy the code
So, just register an entry option, Text2QRCode, on the menu. When the user clicks on it, VSCode will execute the extended activation callback method, get the selected text in the current editor (if not selected, a dialog box will pop up for user input), and then convert the text into the TWO-DIMENSIONAL code image data. Then show the picture through the new TAB.
The above logic is implemented in extension.js:
const vscode = require('vscode');
const Q = require('q');
const QRCode = require('qrcode'); .// Extend the activation callback method
function activate(context) {
let disposable = vscode.commands.registerCommand('extension.text2qrcode'.function () {
getSelectedTextOrPrompt('Text to convert into QR code')
.then(text= > {
if(! text) {return; }
// Convert the text to a qr code image
QRCode.toDataURL(text, {errorCorrectionLevel: 'L'}, function (err, url) {
if(! err) {// Display the qr code image in the new TAB
const panel = vscode.window.createWebviewPanel(
'Text2QRCode'.'Text2QRCode',
vscode.ViewColumn.One,
{}
);
panel.webview.html = getPreviewHtml(url);
} else{ vscode.window.showErrorMessage(err.message); }}); }); }); context.subscriptions.push(disposable); }// Display the two-dimensional code picture
function getPreviewHtml(image) {
return ` <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Word-wrap: break-word! Important; "> <div style="display: flex; min-height: 240px; height: 100%; width: 100%;" > <div style="display: flex; flex: 1; flex-direction: column; justify-content: center;" > <img src="${image}" style="align-self: center;" />
</div>
</div>
</body>
</html>`;
}
// Get the currently selected content or prompt the user for input
function getSelectedTextOrPrompt(prompt) {
const activeTextEditor = vscode.window.activeTextEditor;
if (activeTextEditor) {
const
selection = activeTextEditor.selection,
start = selection.start,
end = selection.end;
if(start.line ! == end.line || start.character ! == end.character) {returnQ(activeTextEditor.document.getText(selection)); }}returnvscode.window.showInputBox({ prompt }); }...Copy the code
At this point, we have completed the development of the extension.
In addition, simply put a breakpoint on the appropriate line of code and press F5 to enter debug mode.
Extended run effect:
Release on
Once the extension is developed, we can package it for release.
First, install the official release script: NPM install -g vsce
Then execute the package script:
$ vsce package ... DONE said: / MNT/g/text2qrcode git/text2qrcode - 1.0.0. Vsix (749.32 KB) 323 files,Copy the code
Now you can send the wrapped extension, text2Qrcode-1.0.0.vsix, to others to use.
Or, upload the extension to the official extension marketplace:
marketplace.visualstudio.com/manage/
This allows you to search and install directly in vscode:
conclusion
Congratulations, you have completed the development of a VSCode extension in 10 minutes, now install and experience!
Don’t forget to make a nice icon for your extension;)
The appendix
- Extend store homepage: marketplace.visualstudio.com/items?itemN…
- Extension source: github.com/Ceelog/text…