Hello everyone, I am cold grass 😈, a grass system code ape πŸ’. Intermittent blood πŸ”₯, continuous sand sculpture 🌟 if you like my article, you can pay attention to βž•, like, and grow with me ~

A prelude to 🎡

I want to read my article must be program ape or program yuan, I do not know what you code with the IDE, anyway, I have been using VScode, cold grass and VScode is a good partner.

Cold grass 🌿 : “vscode, let’s be brothers” vscodeπŸͺ„ : “roll to labor” cold grass 🌿 : “ok, see you tomorrow”

In this way, VSCode and I became good partners. Since we spent a large part of our work dealing with VSCode, and the plug-in capability of VSCode is very powerful, the natural idea came to us: “Can I acquire some knowledge of VSCode plug-in development to optimize my work experience?” , this problem is obvious, everyone’s VSCode should be installed to improve the development efficiency, optimize the development experience of plug-ins, such as:

  • veture
  • eslint
  • todo highlight
  • .

These plug-ins are really helpful for daily work, and their powerful features also confirm my point above:

With the vscode plug-in, we can optimize our work experience

Therefore, we might as well personally through VSCode plug-in development to enhance the capabilities of VSCode we live with day and night, to optimize the purpose of working experience. A while ago I made a VS Code plugin called Fe-File-Rename, which you can already find in the plugin store, and I wrote an article about it: My first VS Code plugin development: Fe-File-Rename && a little bit more

Fe-file-rename Function description:

  1. Modify file names in batches, support underscore, hyphen, big hump, small hump three naming methods, and synchronize to change the reference
  2. When the user changes the file name or changes the file path, the reference is automatically updated (with a switch that can be turned off).

– Only vUE projects are supported for now

I think this VSCode plug-in solves the problem that WHEN I modify the file name or file path, I don’t know where to modify the file reference, and I’m afraid of making mistakes or missing changes, which greatly improves my work experience. Optimizing work experience is an addictive thing. Recently I developed two VSCode plug-ins to optimize my work experience. I will also guide you step by step to find hidden needs in work and then implement them.

Of course, when your plugin appears in the vscode plugin store, it’s also a great sense of accomplishment πŸ”₯ ~

Make 🎡

Create a VScode-extension that belongs to you

The official document: code.visualstudio.com/api scaffolding installation vscode plugin development

npm install -g yo generator-code
Copy the code

The inputyo codeInitialization code

Create a new project is so simple, then I will accompany you to complete two simple but practical VScode plug-ins through my recent two practices 🌟 ~

Console, debugger one-click delete πŸŽ‹

Plug-in name: invalid-code-remover. Welcome to search and download

The following dialogue is adapted from a real job: The innocent cold grass: “I mentioned Mr, you give me one ~” the grumpy leader: “ok… Either! You have a console and a debugger.” Innocent cold grass: “ah ah ah, missed deletion” testy leader: “this kind of code do not bring release up, to delete!”

Console and debugger are often used in daily debugging, and there are many ways to solve the console problem:

  • Check code on submission
  • Compile-time delete

I haven’t seen much of either yet, but since it’s best not to have console and debugger in the release branch (I’m also obsessive and don’t like seeing other people’s console or debugger), there’s a way to do it. To avoid the problem of missing the console and debugger, I chose to solve it by myself. By my means, the first thing I thought of was to use VSCode plug-in. First of all, I would like to clarify my thoughts:

  1. Right-click on a file or directory
  2. Reads all subfiles of the selected file or directory
  3. Replace the in by reconsoleAs well asdebugger
  4. Writes the processed content to a file

Ok, now that we have the idea, let’s start:

"activationEvents": [
    "onCommand:invalid-code-remover.removeConsole"."onCommand:invalid-code-remover.removeDebugger"]."main": "./dist/extension.js"."contributes": {
    "commands": [{"command": "invalid-code-remover.removeConsole"."title": "remove console"
      },
      {
        "command": "invalid-code-remover.removeDebugger"."title": "remove debugger"}]."menus": {
      "explorer/context": [{"command": "invalid-code-remover.removeConsole"."when": "filesExplorerFocus"."group": "navigation@1"
        },
        {
          "command": "invalid-code-remover.removeDebugger"."when": "filesExplorerFocus"."group": "navigation@2"}}}]Copy the code

First, take a look at my configuration items in package.json. First, I have two directives:

  • Invalid code – remover. RemoveConsole delete the console
  • Invalid code – remover. RemoveDebugger delete the debugger

And set their trigger condition to filesExplorerFocus, so that the title of the two instructions appears on the menu that appears when you right-click on a file or directory.

Then let’s look at the contents of the entry file extension.ts:

import * as vscode from 'vscode';
import { removeInvalidCodeEntry } from './handlers';
import { INVALID_TYPE_MAP } from './configs';

export function activate(context: vscode.ExtensionContext) {
	
    const removeConsole = vscode.commands.registerCommand('invalid-code-remover.removeConsole'.(params) = > {
        const isSuccess = removeInvalidCodeEntry(params.fsPath, INVALID_TYPE_MAP.get('CONSOLE'));
        if(isSuccess) {
          vscode.window.showInformationMessage('remove console success! ');
        } else {
          vscode.window.showErrorMessage('remove console failed! '); }});const removeDebugger = vscode.commands.registerCommand('invalid-code-remover.removeDebugger'.(params) = > {
        const isSuccess = removeInvalidCodeEntry(params.fsPath, INVALID_TYPE_MAP.get('DEBUGGER'));
        if(isSuccess) {
            vscode.window.showInformationMessage('remove debugger success! ');
        } else {
          vscode.window.showErrorMessage('remove debugger failed! ');
        }
     });

    context.subscriptions.push(...[removeConsole, removeDebugger]);
}

export function deactivate() {}

Copy the code

You can think of activate as an entry method. I through vscode.com mands registerCommand above two time registration, and the params. FsPath as a parameter, to the way I define removeInvalidCodeEntry, Get (‘CONSOLE’) is used to determine whether the user wants to delete the CONSOLE or the debugger.

Here’s a look at the constants I’ve defined to determine the type of operation and directories or files that don’t need to be involved in deleting console or debugger operations:

export const UN_MATCH = 0;

export const INVALID_TYPE_MAP = new Map([['CONSOLE'.1],
    ['DEBUGGER'.2]]);export const EXCLUDE_DIR_NAME:Set<string> = new Set([
    'public'.'dist'.'node_modules'.'docs'.'test',]);export const EXCLUDE_FILE_EXTNAME:Set<string> = new Set([
    'css'.'sass'.'less'.'md'.'lock'.'json'.'yarnrc'.'svg'.'png'.'gitignore'.'vscodeignore'.' '
]);
Copy the code

Now let’s get to my main event, and I’ll put what I want to say in the comments:

import { UN_MATCH, INVALID_TYPE_MAP, EXCLUDE_DIR_NAME, EXCLUDE_FILE_EXTNAME } from '.. /configs';
import { lstatSync, readFileSync, writeFileSync, existsSync, readdirSync } from 'fs';
import { join, basename, extname } from 'path';

// Encapsulate the isDir method to determine whether it is a directory or a file
function isDir(path: string) :boolean {
  const stat = lstatSync(path);
  return stat.isDirectory();
}

export function removeInvalidCodeEntry(path: string, type: number = UN_MATCH) :boolean {
  // Return false if the operation type is not one of the accepted types;
  if (type === UN_MATCH) {
    return false;
  }
  // If the passed file path does not exist, RETURN false;
  if(! existsSync(path)) {return false;
  }
  // If an exception occurs, RETURN false;
  try {
    if (isDir(path)) {
      // The directories in the constants above do not need to be processed
      if(EXCLUDE_DIR_NAME.has(basename(path))) {
        return true;
      }
      // If it is a directory, retrieve its subfiles and recurse
      const files = readdirSync(path);
      files.forEach((file: any) = > {
        const subPath = join(path, file);
        removeInvalidCodeEntry(subPath, type);
      });
    } else {
      Return if the file type does not need to be processed
      if(EXCLUDE_FILE_EXTNAME.has(`.${extname(path)}`)) {
        return true;
      }
      const fileOptions = { encoding: 'utf-8' as BufferEncoding };
      const content = readFileSync(path, fileOptions);
      // I read the file and replace it line by line for reasons I'll explain later
      const lines = content.split('\n');
      const handledLines = [];
      // Delete console and debugger line by line
      for (const line of lines) {
        let handledLine = ' ';
        switch (type) {
          case (INVALID_TYPE_MAP.get("CONSOLE")):
            handledLine = line.replace(/console\.. * \ \ (. *) (*). ? /g.' ');
            break;
          case (INVALID_TYPE_MAP.get("DEBUGGER")):
            handledLine = line.replace(/debugger( )*; ? /g.' ');
            break;
          default:
            handledLine = line;
            break;
        }
        if (handledLine === line || !* $/ / ^ ().test(handledLine)) { handledLines.push(handledLine); }}let handledContent = handledLines.join('\n');
      // Write to the file. Of course, if the file has not changed, no write is required
      if (handledContent !== content) {
        writeFileSync(path, handledContent, fileOptions);
      }
    }
    return true;
  } catch(err) {
    return false; }}Copy the code

So why do we use a progressive traversal to delete console or debugger?

I think most engineers will have code obsessive, if you use my plug-in, after the console, debugger deleted, but there is a blank line, is not very obsessive. So I use line-by-line processing, and if the replaced line becomes blank, I don’t push, so I keep the original file format.

Here’s what it looks like:

The format does not affect ~ perfection at all ✨ ~

Go download it at πŸ”₯

Configure your own code snippet πŸŽ‹

Plugin name: Trantor-MD-Snippets, welcome to search and download

Recently I’ve been documenting common components and designing system refactorings, which have a lot of common formats in them, but it’s a pain to have to copy and paste them somewhere else.

// For example, this common form# # # # Attributes | | parameters shows that default value type | | | | -- - | -- - | -- - | -- - | | | | | |// For example, this uml@startuml top to bottom direction Component Name --props-- --events-- --methods-- --slots--] sub-component -> @ enduml parent componentCopy the code

So I want to use vscode plug-in code snippet to solve this problem, I simply type two letters, press a Tab, kua, template out, I directly on the above to write ~ so say to do, for my work happiness, say to do to do!

This time, it’s easier to look at package.json:

"categories": [
    "Snippets"]."contributes": {
    "snippets": [{"language": "markdown"."path": "./snippets.json"}},Copy the code

I have restricted this plugin to only work in MarkDown. Then check out my snippets.json:

{
"Design Document: View Component Diagram": {
        "prefix": "Components"."body": [
            "@startuml"."top to bottom direction"."Component ${1: component name} ["."${2: Component Description}"."${3: component name hyphenated}"."--props--"."$4"."--events--"."$5"."--methods--"."$6"."--slots--"."$7"."]".${8: child} -> ${9: parent}"."@enduml"]."description": "Design Document: View Component Diagram"},... }Copy the code

Here’s just one example. When I type Components, I get a prompt like this:

Press Tab, and this code snippet appears:

Of course, if you have plantUML installed, you can try it directly:

I will also share with you how to do front-end design, please look forward to ~

Tail plays 🎡

Write the eggs on Tanabata πŸŽ‹

Today again to the Chinese Valentine’s Day, is a person, the window of Beijing under the rain 🌧️, the window of the cabin alone to write. The code of this article is written on the Chinese Valentine’s Day, the article began to code on the rainy night of the Chinese Valentine’s Day, in fact, this chapter is I do before writing the text, think ha ha ha, I think I don’t know what content to take in this chapter, but always want to write something special in this ordinary and special day. I was actually writing a little introduction to our front end team recently, and someone said to me, “I can write thousands of words, I think you have a talent for writing novels!” , aye? Well, I’ll write a short essay in this chapter, and then you’ll know that I don’t have the talent to write novels, so let’s start now, cold grass’s impromptu bedtime story:

The rain kept falling, splashing against the baffle. The boy sat in front of his desk in a daze, do not know what to write, suddenly mobile phone vibration, “toot toot”, scared the boy a shock, but also be his thoughts back to the real world.

“Who’s going to text me? Adsell again,” the boy thought. Open the mobile phone to see, is a strange number, the normal mobile phone number is 11, this number visually has more than 20… The boy looked at the content is also confused, the message is full of baffling characters, interspersed with a few Chinese characters:

β€œYou, not, four hundred, test, try, words

Followed the boy involuntarily to read a few known words in the text, “puzzling, what thing ah, again is a junk messages”, then also did not want to put more mobile phone aside, towards the window, put their hands on the glass, as if can feel the rain beating in his own skin, he is only a piece of glass from the distance, but it seems so far away. With a sigh, the boy returned to the bed and lay down arbitrarily, looking straight at the oxidized ceiling with a little yellow, sighed, closed his eyes and fell asleep.

.

The next morning, the boy was awakened by a noise, only to hear the corridor shouted, “it’s your turn! Today is the day you can fucking leave the house! The next time you try to go outside, I’ll break your legs and lock you up for three more months.”

“That brother trying to escape again… Don’t knowoutsideWhat’s good, “the boy cried rip-off, turn to look out of the window, and just a little bit brighter than night, as if with the dust in the air, faintly visible outside the skyscrapers of sending out the magic eerie light,” and don’t want to think, what attracts people to the world outside, cut “, the boy caught catch hair, picked up the side of the mobile phone, astonished at the scene made his eyes.

99 +!

Oh, my God, the boy’s been here for five months, and he hasn’t heard 99 messages. The messages were all from yesterday’s strange number, and the boy could only see repeats at first:

β€œCall me when you get it

β€œCall me when you get it

β€œCall me when you get it

After scrolling up for a long time, I finally saw the first few messages:

β€œAh, I forgot to switch to the code format of your time, it should be fine now, please listen to me

The boy swallowed and read on:

β€œHello, dish dog son, I come from the future, yes, four hundred years in the future, I am conducting an experiment, trying to save the world of the great experiment, need your help, let us a time and space through the rescue operation ~

β€œWhy don’t you talk back and save the world?

β€œSure enough, it was a vegetable dog

β€œSmelly brother,

β€œEmmm, call me back

.

β€œCall me when you get it

At one point, the boy could not understand each other’s words, and even thought that the other might be a mental illness. But after staying in this boring life day after day for a long time, he suddenly felt a little surprise. He held the phone tightly and typed a few words carefully:

β€œI was, I was sleeping… Is there anything I can do for you?“The boy scrutinized the words on the screen and tapped Send.

Send in…

Send in…

Loading turned around a few times before finally a green checkmark appeared on the screen

Send a success

The phone vibrated. Yes, it was the same number. It was short and full of energy:

“Finally reply, ha ha ha, then, our storyTo start once again🌟”

“Again… Start again? !”

If someone expects it, it's to be continued

Also, Tanabata custom not only cold grass improvisation of the novel, and Tanabata custom eggs – meteor shower 🌠

Here I wish you all (reading here) wishes come true, shining ~

Hey, I am single to give this meteor shower to who

Write at the end of the last πŸŽ‹

Then this article is over. Vscode plug-in has strong capabilities, but the document reading experience is not very good. Every time I write VSCode plug-in, I always have to go through a relearning process. Stay tuned.

If you like my article πŸ“–, you might as well like βž• attention, for me this grass code ape accumulate magic, your support is my biggest motivation 🌟

Readers, may our future can be expected, may we have a long future, the next article πŸ”₯ ~

Add me on wechat: Hancao97, invite you to join the group, understand the github group of cold grass 🌿, learn front end together, become a better engineer ~ (QR code here -> communication group)