Every time I change my job to a pit, I have to reinstall all kinds of environment, install a vscode plug-in, but vscode plug-in you really know, today we are going to talk about the most common development of a plug-in, called snippets, you can also build a plug-in to release to the app market.

What is the Snippets

Coding theater

(The plot is pure fiction, if there is the same, let me copy you)

Ah Qiang is the company’s outstanding front-end raiding lion, crisp mechanical keyboard tapping sound, slightly backward hairline is a symbol of his identity, excellent front-end knowledge system allows him to deal with a variety of products on the demand after tearing every day.

With more than 20 years of single hand speed, A Qiang can check the deadline to complete his work every time, the position of the leader was firmly held by him.

It is another usual day, the project team came to a new front-end city lion, named a yong, a yong hair amazing, development code never use mechanical keyboard, immersed in the front-end visualization for many years.

A strong surface placidness, but the heart of a yong hair amount quite envy, because sitting in his back of the table, naturally on the new front of a yong had an interest.

After a week, A Qiang through keen observation found that a yong began to use the code pace is very fast, less than two days into the formal development stage. And use two days to put this week’s function to the development of finished, pre-hair on the green through the small icon is a yong’s symbol of victory, during the occasionally go to the front desk and a strong goddess – Jane chat, which makes a strong head big man, produced a trace of anxiety.

A strong heart meditation: it is time to take the initiative to attack

A Qiang began to give Jane love breakfast every day, but also a yong intentional or unintentional communication, starting from the hair treatment, and then to all kinds of front-end frame iteration characteristics. A week later, A Qiang finally revealed the secret of A Yong’s high efficiency:

He installed various snippets plug-ins in vscode and knew the abbreviations by heart.

Ah Qiang eagerly installed the Snippets plug-in and found that he had done more with half the effort. He sipped a sip of Pu-erh goji tea and squinted at the hair transplant AD nearby, his mouth slightly raised.

Code snippet

Code snippets are used to input predefined template code to make coding faster. For example, TSRFC stands for typescript React Function Component. This will be followed by some description information.

Select the first option in the drop-down to display the template information shown below.

snippetsIt is also tied to the development language, which may vary from language to languagesnippets, such ascomputedThe parameter will only be invueIn effect,reactThere’s no such thing. In order not to mix things up,vscodeThe mechanism for doing different mappings for different languages is built into the configurationsnippetsWhen,vscodeYou will be given priority in choosing the language you want to work with.

In fact, there was a paragraph (portal) in the previous article about configuring snippets in a native vscode development environment. This is the easiest way to customize the snippets, but there are some disadvantages:

The first problem is that the configuration of snippets is a JSON file. In the figure below, the body can only accept a single line string or an array of strings, which requires a round of formatting to copy and paste the usual code.

The second problem is that if I change a machine to develop, some of the template configurations I have accumulated have to be re-typed, and different languages have to be differentiated, which is very troublesome to migrate.

Plug-in market

Vscode’s plugin market is very rich, in which you can not only find some general language highlighting, theme support, code check and other development plug-ins, but also brush leetcode, play a small overseer paddling 🐶.

So it’s a great way to maintain snippets using vscode plugins. There are snippets in various languages in the vscode plugin market. Here are the results.

For example, if you click on a Snippets plugin for React, there will be a list of prefix-related templates in the details, and you’ll remember the abbreviations as you get used to them.

In addition to the React snippets shown above, here are a few common front-end snippets based on my own development experience:

  1. HTML Snippets

Support for all HTML5 features

Search for ‘html-snippets’

  1. JavaScript (ES6) code snippets

Js plug-in that supports ES6 syntax

Search keywords: javascriptsnippets

  1. Vetur

Powerful Vue plugin, not just snippets, but syntax highlighting, formatting verification, etc

Search keywords: vetur

  1. Ant Design Snippets

You read that right, ANTD also has its own snippets

Search for antD-Snippets

  1. Flutter Widget Snippets

Flutter has so many built-in components that managing it in a snippets way is a good choice

Search for “flutter-snippets”

Custom plug-in

Plug-ins that use the plug-in market are generally generic, which means you need a list of maps to see the template code, but if you don’t find the snippets you need in the plug-in market, you can build your own plug-in and distribute it without worrying about changing environments. You don’t have to memorize some prefixes.

Step1 install scaffolding and build the project

NPM install -g yo generator-code install global scaffolding yo code run scaffoldingCopy the code

After the scaffolding runs, you need to fill in some configuration, such as what type of plug-in to select, as shown below. Here you need to select New Code Snippets, and then some name, description, language, etc

After all the configuration is finished, it will generate a project that can be immediately developed and debugged, the structure of the project and our usual front-end developmentnpmMode error, the development language is ALSO TS or JS, as shown in the figure below:

Pressing F5 brings up a new window, which is the debug IDE, where code takes effect for the snippets configuration.

Step2 configuration snippets

Look at the package.json of the project and you’ll find that the contributes snippets property contains the mapping of the language and the associated snippets configuration. Clicking on the snippets.code-snippets file will reveal that this is an empty JSON file. To write content, the format is exactly the same as the JSON configuration mentioned above.

So the problem is that we are still configuring the JSON file. The body problem mentioned above is still not solved, and it is still quite troublesome to configure. Don’t panic, we can actually write a script statement to convert our normal code.

The example path is full of template code, snippets. Json is my final OUTPUT JSON file, and the core conversion script is in compiler.js.

${} is an editable template string. The colon is followed by the default value, and the number represents the order in which the edits were made. MemoizedCallback, for example, presses Tab to go to the next doSomething after editing.

Compiler. Js as follows:

const fs = require('fs')
const path = require('path')

// example Specifies the absolute path to the directory
const exampleDir = path.resolve(__dirname, 'example')
// Outputs the JSON configuration directory
const outputDir = path.resolve(__dirname, 'snippets')

// Initialize the code snippet JSON
const snippetsMap = {}

const readDir = (rootDir) = > {
  const fileList = fs.readdirSync(rootDir)
  if (fileList.length > 0) {
    fileList.forEach(fileName= > {
      const filePath = path.join(rootDir, fileName)
      const statInfo = fs.statSync(filePath)
      // Continue traversing if it is a directory
      if (statInfo.isDirectory()) {
        readDir(filePath)
      } else if (statInfo.isFile()) {
        handleFile(filePath, fileName)
      }
    })
  }
}

// Process files
const handleFile = (filePath, fileName) = > {
  let name = fileName.split('. ') [0]
  let prefix = fileName.split('. ') [0]
  let des = ' '
  const bodyList = []

  const fileInfo = fs.readFileSync(filePath, 'utf8')
  const lineSplits = fileInfo.split('\n')

  // Line by line, name, description, prefix is extracted
  lineSplits.forEach(line= > {
    const nameReg = /\/\/\s+@name:\s*(.*)/
    const prefixReg = /\/\/\s+@prefix:\s*(.*)/
    const desReg = /\/\/\s+@description:\s*(.*)/
    if (nameReg.test(line)) {
      name = line.match(nameReg)[1]}else if (prefixReg.test(line)) {
      prefix = line.match(prefixReg)[1]}else if (desReg.test(line)) {
      des = line.match(desReg)[1]}else {
      bodyList.push(line)
    }
  })

  snippetsMap[name] = {
    prefix,
    body: bodyList.length > 1 ? bodyList : bodyList[0].description: des
  }
}

readDir(exampleDir)

fs.writeFile(path.join(outputDir, 'snippets.json'), JSON.stringify(snippetsMap, null.2), (err) = > {
  if (err) throw err;
  console.log('write success')})Copy the code

Compiler.js does a few things:

  • traverseexampleAll files under
  • Extract some comment information and use it asnameordescription 
  • Output write intosnippets.json 

Step3 publish the plug-in

Publishing plug-ins requires a command-line tool, vsCE

npm install -g vsce
Copy the code

My way is to package it into a.vsix file and upload it. The package command is as follows

vsce package
Copy the code

After completing the package, go to Azure’s official console to upload it

You may need to create a new organization for Azure. See the following documentation:

portal

I maintain a snippets plugin for React. Search for react-tsX-links-snippets with the following keywords:

Welcome to send me an issue on Github for improvement ~~

Github project address: github.com/Tinsson/rea…

The end of the

Snippets are a tool that helps us be more efficient, and that’s how we get rid of 996. I want you to be flexible in your work and spawn your own Snippets.

Creation is not easy, hope to dig a lot of praise + pay attention to erlian, continue to update!!

PS: If there are any mistakes in this article, please kindly correct them

Past wonderful 📌

  • Vue3 check this out ✨ before building the “hooks” wheel
  • Open react-redux ✨ using Hooks
  • React Hooks✨
  • React DevTools ✨
  • Vue3 hugs TypeScript properly ✨
  • Vue3-one piece尝鲜:React Hooks VS Composition API ✨

Public number: front end small DT

Reference article 📚 :

  • Vscode plug-in development guide
  • Introduce vscode snippet