Original is not easy, I hope you can pay attention to us, and then easily point a praise ~~
This article was first published on the blog of the front end team of the political cloud: DIY VSCode plug-in, so that your development efficiency leaps forward
preface
Visual Studio Code (referred to as VSCode) stands out from many ides due to its features of small memory, fast file loading, good stability, rich plug-ins and so on, and is favored by the majority of developers. To do a good job, he must sharpen his tools. Choosing the right VSCode plug-in for you can make your development productivity soar. The VSCode plug-in market is full of plugins, but the actual development process is complicated and changeable, sometimes can not find a plug-in to fully meet your actual development needs, then DIY yourself. VSCode offers the following extensions: code completion, custom commands/menus/shortcuts, hover hints, custom jumps, theme customization, custom webviews, and more. You can use any combination you want.
Quick learning
Next, we will use a simple code fragment autocomplete plug-in as an example to get you started in 10 minutes. Snippet completion is also the most frequently used feature to help speed up coding. The Demo source code
Preparing for development Environment
-
Visual Studio Code
-
Nodejs, the LTS version is recommended
-
Npm
-
The official recommended scaffolding tools are Yeoman and Generator-code
npm install -g yo generator-code Copy the code
-
The plug-in packaging and publishing tool VSCE
npm install -g vsce Copy the code
Scaffolding use
- Run the following command:
yo code
Copy the code
- Select the New Extension type, then fill in the basic information of the plug-in name, description, package management tool, and so on.
PS: Scaffolding tools Support creation of plug-ins (New Extension), themes (New Color Theme), New Language Support (New Code Snippets), keyboard maps (New) Keymap, New Extension Pack. The above different types of scaffold templates focus only on different default functions, which are essentially VSCode plug-ins.
Automatic completion of Snippets
- Add a Snippets configuration item
// package.json ... "contributes": { "snippets": [ { "language": "javascript", "path": "./snippets/javascript.json" }, { "language": "typescript", "path": "./snippets/javascript.json" }, ... ] },...Copy the code
Add custom Snippets under package.json contributes. Language indicates that the corresponding snippet of code is loaded only in a particular language. Path indicates the path where the code snippet file is stored. The configuration above indicates that the javascript or typescript language environment, will load. / snippets of javascript. The code snippet in the json file.
- Write Snippets
// ./snippets/javascript.json { "forEach": { "prefix": "fe", "body": [ "${1:array}.forEach(function(item) {", "\t${2:// body}", "});" ] , "description": "Code snippet for \"forEach\"" }, "setTimeout": { "prefix": "st", "body": [ "setTimeout(function() {", "\t${0:// body}", "}, ${1:1000});" ] , "description": "Code snippet for 'setTimeout'" } ... }Copy the code
In the above examples:
- ForEach and setTimeout are the names of snippets.
- Prefix defines one or more trigger words (multiple can be specified when setting array). When the user enters a trigger word, the editor will pop up an auto-completion prompt.
- bodyIs defined to fill the snippet content. A placeholder can be used in the body, as shown above
${1:array}
,{2:// body}
, the use of placeholders is convenient to reference code segments can be quickly switched to the corresponding position by TAB key editing. The ordinal number before the colon indicates the switching order, and the text after the colon is the default text for the placeholder display. - Description, as the name implies, is the description of the code segment. The editor displays the description when the completion prompt is displayed. If the description field is not set, the code segment name is displayed directly.
At this point, the code of the plug-in is complete, is not very simple ~ next, let’s run the plug-in to see the effect.
Run the debug
Select VSCode’s debug menu (command+shift+D), click the run button, and a window named extension development host pops up. This window is the temporary debug window that contains the plug-in.
Packaging and publishing
packaging
Package command: vsce package, after the package is completed, the installation package with the.vsix suffix will be generated. If the plug-in is only shared among individuals or teams, it can be installed manually and used without being released to the VSCode plug-in marketplace.
release
Publish command: vsce publish To publish, you need to go to Azure DevOps to register. After registering, you need to apply for Personal Access Tokens. See the documentation for details.
The plugin,
The directory structure
.├ ──.vsCode ├─ launch.jsonConfiguration for plug-in loading and debugging├ ─ ─ CHANGELOG. The md# change record├ ─ ─ the extension. JsPlugin execution entry file├ ─ ─ jsconfig. Json# JavaScript type check configuration├─ node_modules ├─ Package-Lock. json ├─ Package.jsonDeclare information about the current plug-in├ ─ ─ the README, md# Plugin instructions└ ─ ─ VSC - the extension - quickstart. MdCopy the code
The core file
1. Package. json: declaration file of the plug-in, which contains 2 important configuration items activationEvents, contributes.
- ActivationEvents is used to define when the plug-in is loaded/activated. In this example, onCommand is used, and the plug-in is only activated when the Hello World command is invoked. Currently, nine activation events are supported:
onLanguage:${language}
When you open a language-specific fileonCommand:${command}
When a VSCode command is calledonDebug
When the DebugworkspaceContains:${toplevelfilename}
When you open a folder that contains a naming ruleonFileSystem:${scheme}
Open a file or folder using a certain protocol (FTP, SFTP, SSH, etc.)onView:${viewId}
When the view with the specified ID is expandedonUri
When the system-level URI of the plug-in is openedonWebviewPanel
The webview activates*
VSCode starts. Do not use it, because performance may be affected.
PS: For performance reasons, plug-ins are lazily loaded and only loaded/activated in specific scenarios, consuming memory and other resources.
- Contributes defines the specific configuration of the extension. Common extensions include snippets, commands, menus, keybindings, and themes. Typically, after a command is developed, it is associated with a menu/shortcut key for invocation.
// package.json {// plugin name" name": "vscode-test-extension", // displayName" displayName": "Vscode-test-extension ", // description: "An awesome VScode extension", // version number semver format "version": PNG ", "publisher": "chenmenglan", // the lowest supported version of vscode for the plugin "engines": {" vscode ":" ^ 1.12.0 "}, / / the category, optional Languages/Snippets/Linters/Themes/Other etc "categories" : [" Snippets ", "Other"], / / loading/activate "activationEvents" : [" onCommand: extension. The helloWorld "], / / "main" entry file path: Js ", // contributes extension configuration "contributes": {" Commands ": [{"command": "extension.helloworld ", "title": "Hello World" } ], "snippets": [ { "language": "javascript", "path": "./snippets/javascript.json" }, ... ] }}Copy the code
2. Extension. js: The execution entry file of the plug-in, usually including two methods: activate and deactivate. Command must use vscode.com mands. RegisterCommand register, and then returns an instance of the added to the context. The subscriptions. When the command is activated, the corresponding callback method is executed.
const vscode = require('vscode');
/** * @param {vscode.ExtensionContext} context */
function activate(context) {
console.log('Congratulations, your extension "vscode-test-extension" is now active! ');
let disposable = vscode.commands.registerCommand('extension.helloWorld'.function () {
// A message is displayed in the lower right corner
vscode.window.showInformationMessage('Hello World! ');
});
context.subscriptions.push(disposable);
}
exports.activate = activate;
function deactivate() {}
exports.deactivate = deactivate;
Copy the code
conclusion
If you’ve been working on the same problem more than three times, it’s time to stop and think about how to simplify things. Take the time to comb through the most frequently used or best practice code snippets, create your own plug-in, and focus on the more core and complex code logic. Rich extension apis make everything easier than you think, Just do what you want~
The plugin is recommended
Auto Close Tag: indicates the closing Tag of Auto completion.
Auto Rename Tag: automatically renames a label.
Bracket Pair Colorizer makes it easier to view multiple layers of nested code.
Beautify, quick formatting code.
ESLint, syntax rule and code style checker
Path Autocomplete, automatic file Path completion.
Document This, quick comment generation.
Todo Highlighter, which highlights Todo comments to make it easier to track any unfinished business.
GitLens enhances Git functionality built into VSCode, including viewing code authors, viewing historical commits, and more.
There are other useful plug-ins, welcome to add ~~
, recruiting
ZooTeam, more than 50 partners are waiting for you to join the wave ~ If you want to change things have been torturing, I hope to start torturing things; If you want to change, you’ve been told you need more ideas, but you don’t have a solution. If you want change, you have the power to make it happen, but you don’t need it. If you want to change what you want to accomplish, you need a team to support you, but you don’t have the position to lead people. If you want to change “5 years of work and 3 years of experience”; If you want to change the original savvy is good, but there is always a layer of fuzzy window… If you believe in the power of believing, believing that ordinary people can achieve extraordinary things, believing that you can meet a better version of yourself. If you want to be a part of the growth of a front end team that has deep business understanding, technology systems, value creation, and impact spillover as the business takes off, I think we should talk. Any time, waiting for you to write something and send it to [email protected]
Recommended reading
Serverless Primer for front-end engineers
Visual Construction System for Front-end Engineering Practice (PART 1)
After reading this, you can play React Hooks, too
Automated Web performance optimization analysis solution