Skip to content

Instantly share code, notes, and snippets.

@fredjoseph
Last active April 26, 2023 20:42
Show Gist options
  • Select an option

  • Save fredjoseph/a7bfad80d982e8293388601ea6ee1377 to your computer and use it in GitHub Desktop.

Select an option

Save fredjoseph/a7bfad80d982e8293388601ea6ee1377 to your computer and use it in GitHub Desktop.
VSCode - Tips

Une version light est disponible en ligne à l'adresse vscode.dev et permet de consulter/éditer rapidement des fichiers dans le cas où vous n'êtes pas sur votre poste personnel ou dans l'impossibilité d'installer VsCode sur celui-ci.

Tips

  • Save extensions
    code --list-extensions > vscode-extensions.list
  • Restore extensions
    cat vscode-extensions.list | xargs -L 1 code --install-extension
  • Disable all Extensions for a session
    code --disable-extensions
  • Load with an alternate extensions directory
    code --extensions-dir <dir>

Issues

Experiencing slowness or a blank screen

VS Code has trouble with GPU (graphics processing unit) hardware acceleration on some systems. You can see if this is the case by disabling GPU acceleration.

code --disable-gpu

To set this permanently, do the following:

  • Open the Command Palette (Ctrl+Shift+P).
  • Run the Preferences: Configure Runtime Arguments command.
  • This command will open a argv.json file to configure runtime arguments. You might see some default arguments already there.
  • Add "disable-hardware-acceleration": true.
  • Restart VS Code.

Typescript - Absolute auto-imports instead of relative ones

By default, Vscode will auto imports modules with the shorter path between the relative path and the absolute path from the basePath defined in tsconfig.json.

One workaround is to create a new tsconfig.json file extending the default one of the project and to define a new basePath in it pointing to a non-parent directory (the path aliases must be overriden too). This file should be excluded from git. By overriding the basePath to a non-parent directory, all auto-import paths will be resolved with a relative one.

Go to Definition - go to local sources instead of node_modulesfiles

By default, the command Ctrl + click allows you to navigate to the definition of an identifier. If this identifier is defined in a dependency, you will navigate to its definition in the node_modules folder even if you use a symbolic link in your node_modules to use the latest source version of the dependency (npm link or yarn link).

One workaround is to create a new tsconfig.json file extending the default one of the project and to define path aliases mapped to the physical locations of the dependencies you want to override. This new file must be written in a parent directory of the source code (to be visible by all file locations) but in a child folder of the original tsconfig.json file to be overridden.

project
|__tsconfig.json
\__src
   |__tsconfig.json
   |__main.ts

For example: If you use a toolkit dependency and the import of an identifier from it looks like:
import { MyClass } from '@company/toolkit/...'
Thanks to the following path alias, you will navigate to the real source.
"@company/toolkit/*": [ "<relative_path_to_toolkit_project>/*" ]

{
  "extends": "../tsconfig",
  "paths": {
  "@company/toolkit/*": [ "<relative_path_to_toolkit_project>/*" ]
  }
}

This file should be excluded from git.

ℹ️ This workaround is only required if the global tsconfig contains a default path to the node modules "*": [ "./node_modules/*", "*"].
Without this line, the default behavior is already as desired.

Auto-import transitive dependency

By default, VSCode cannot suggest an import path for a transitive dependency. This is for a very good reason: if your project doesn't have a dependency declared in its package.json, it should not using it directly (so, should not import something from it). The reason is there is no garanty to find this library in node-modules if the project doesn't have it as a direct dependency.

A workaround is to add a new package.json file in the parent directory of your projet and add in it all transitive dependencies that we are sure to have it later and on which we want to be able to do auto-import (for example, if the project uses a private corporate toolkit library, you can create a symbolic link of the toolkit's package.json in the parent directory of your project).

Slow Startup Time

When VS Code starts up, some extensions are loaded with it. So when your application doesn’t start instantly, it might not be caused by the software itself, but due to loading too many extensions. You can use the command palette to run the command: Developer: Show Running Extensions to check the activation time of each extension.

Settings

Brackets Highlight

This feature doesn't require a specific extension (aka Bracket Pair Colorizer 2). It can be activated through the setting :

"workbench.colorCustomizations" : {
    "editorBracketMatch.background": "#fbff0b83",
    "editorBracketMatch.border": "#fbff0b83",
    "editorIndentGuide.activeBackground": "#fbff0b83",
    "tab.activeBorder": "#fbff0b83",
}

Native Bracket Pair Colorization (since version 1.60)

This feature is implemented to address performance issues of the famous Bracket Pair Colorizer extension and can be activated through the setting:

"editor.bracketPairColorization.enabled": true,
"editor.guides.bracketPairs": true,	// since version 1.61, possible values: true, false, "active" (only show guide for active bracket pair) 

The colors can be customized with the settings

"workbench.colorCustomizations": {
    "editorBracketPairGuide.background{1...6}": "#FFB86C",
    "editorBracketPairGuide.activeBackground{1...6}": "#FFB86C",
}

ℹ️ My current configuration is to show guide only for the active bracket pair with the same color as the one used in the editorBracketMatch (whatever level it is). My bracketPairColorization setting is currently disabled

Native inlay hints for JavaScript and TypeScript (since version 1.60)

The most significant new tooling feature in TypeScript 4.4 is inlay hint support. Inlay hints add additional inline information to source code to help you understand what the code does.

ℹ️ This native feature replaces the extension Parameter Hints if your project uses a TypeScript version >= 4.4

To enable parameter name hints, set javascript.inlayHints.parameterNames.enabled or typescript.inlayHints.parameterNames.enabled settings. There are three possible values:

  • none - Disable parameter inlay hints.
  • literals - Only show inlay hints for literals (string, number, Boolean).
  • all - Show inlay hints for all arguments.

Other available inlay hints:

  • Variable type inlay hints show the types of variables that don't have explicit type annotations javascript.inlayHints.variableTypes.enabled and typescript.inlayHints.variableTypes.enabled
  • Property type inlay hints show the type of class properties that don't have an explicit type annotation. javascript.inlayHints.propertyDeclarationTypes.enabled and typescript.inlayHints.propertyDeclarationTypes.enabled
  • Parameter type hints show the types of implicitly typed parameters. javascript.inlayHints.parameterTypes.enabled and typescript.inlayHints.parameterTypes.enabled
  • Return type inlay hints show the return types of functions that don't have an explicit type annotation. javascript.inlayHints.functionLikeReturnTypes.enabled and typescript.inlayHints.functionLikeReturnTypes.enabled

Synchronizing Settings

VS Code now supports synchronizing VS Code settings across different machines (replaces the extension Settings Sync). User Guide

Auto import modules

Automatically import JavaScript and TypeScript modules based on your code (replaces Auto import, Move TS - Move TypeScript files and update relative imports and Auto Import - ES6, TS, JSX, TSX).

  • Settings
    • JavaScript > Suggest: Auto Imports: "Enable/disable auto import suggestions. Requires using Typescript 2.6.1 or newer in workspace." Default value is true.
    • TypeScript > Suggest: Auto Imports: "Enable/disable auto import suggestions. Requires using Typescript 2.6.1 or newer in workspace." Default value is true.
    • JavaScript > Update Imports on File Move: Enabled: "Enable/disable automatic updating of import paths when you rename or move a file in VS Code. Require using TypeScript 2.9 or newer in the workspace." Default value is "prompt".
    • TypeScript > Update Imports on File Move: Enabled: "Enable/disable automatic updating of import paths when you rename or move a file in VS Code. Require using TypeScript 2.9 or newer in the workspace." Default value is "prompt".
"javascript.suggest.autoImports": true,
"typescript.suggest.autoImports": true,
"javascript.updateImportsOnFileMove.enabled": "always",
"typescript.updateImportsOnFileMove.enabled": "always",

Also, if you would like your imports to be organised when you save, you can add the setting below. It will remove unused import statements, and arrange import statements with absolute paths on top. I am a big fan of these kind of set-and-forget tasks.

"editor.codeActionsOnSave": {
    "source.organizeImports": true
}

Autotrimming

Remove trailing whitespace automatically (replaces the extension Autotrim). It can be activated through the setting :

  • Files : Trim Trailing Whitespace: "When enabled, will trim trailing whitespace when saving a file." The default value is false.
"files.trimTrailingWhitespace": true

Format Modified Code on Save

Format modified lines on save can be activated through the settings:

"editor.formatOnSaveMode": "modifications",
"editor.formatOnSave": true,

Status bar for suggestions

The suggestions control can now also show its own status bar at the bottom of the window. Enable it using the editor.suggest.showStatusBar setting. It makes toggling details simpler, and shows if a completion supports inserting, replacing, or both.

"editor.suggest.showStatusBar": true,

The new editor.suggest.insertMode setting allows you to configure whether you prefer insert or replace. When a suggestion supports both, your preference will be the default

"editor.suggest.insertMode": "replace",

Reduce file watchers

Visual Studio Code's auto-completion or IntelliSense actually uses a Universal LSP(Language Server Protocol) package which are some bunch of file watchers. This package uses other language specific packages to watch each individual file for matching types or for intellisense. Well, that's okay & completely fine when your project is small.

We can reduce the number of file watchers on the settings:

  //exludes files & folders in search indexing
  "search.exclude": {
    "**/node_modules": true,
    "**/bower_components": true
  },
  //exludes fies & folders for watcher service
  "files.watcherExclude": {
    "**/.git/objects/**": true,
    "**/.git/subtree-cache/**": true,
    "**/node_modules/**": true
  },

Disabling unwanted extensions for workspace

Disabling @builtin extensions that are not important for your project's stack can make VSCode a bit lighter too. Although most of the time these aren't even started by VSCode's extension host beacause VSCode doesn't start an extension unless you need it. You can do this by searching in VSCode's extension tab with @builtin tag. It'll show all the builtin extensions.

Auto renaming tags (Rename HTML and XML tag pairs with a single edit)

This feature doesn't require a specific extension (aka Auto Rename Tag). It can be activated through the setting :

  • Editor: Rename on Type: "Controls whether the editor auto renames on type." Default is false.
"editor.renameOnType": true

Color Customization

Color themes let you modify the colors in Visual Studio Code's user interface to suit your preferences and work environment Guide To find the scope associated to a text, we can use in Command Palette: Developer: Inspect Editor Tokens and Scopes

My current customization :

"editor.tokenColorCustomizations": {
	"[Default Dark+]": {
		"textMateRules": [
			{
				"scope": [
					"variable.parameter"
				],
				"settings": {
					"fontStyle": "italic",
					"foreground": "#ceb54f"
				}
			},
		]
	}
},

Open Editors sorting

"explorer.openEditors.sortOrder": "alphabetical"

HTML Alignment

Change the setting html.format.wrapAttributes with one of the following values

- auto: Wrap attributes only when line length is exceeded.
- force: Wrap each attribute except first.
- force-aligned: Wrap each attribute except first and keep aligned.
- force-expand-multiline: Wrap each attribute.
- aligned-multiple: Wrap when line length is exceeded, align attributes vertically.
- preserve: Preserve wrapping of attributes
- preserve-aligned: Preserve wrapping of attributes but align

Extensions

See also VSCode - Performance

Code

⚠️ This extension is great, but you can experience high cpu usage and slowness by using it. If you only need to distinguish the block of code where you are, you should replace this extension by the native bracket highlight feature. :warning: The editor supports native bracket pair colorization since version 1.60

⚠️ This extension bundle is not optimized (contains unnecessary files) and is activated at startup. A better alternative is HTML CSS Support.

⚠️ This extension is activated at startup (not optimized).

  "importSorter.sortConfiguration.customOrderingRules.rules": [
    {
      "type": "importMember",
      "regex": "^$",
      "orderLevel": 40,
      "disableSort": true
    },
    // Add your specific rules here (from the more specific rule to the more global one)
    //{
    //  "regex": "^toolkit",
    //  "orderLevel": 21
    //},
    //{
    //  "regex": "^shared",
    //  "orderLevel": 22
    //}, 
    {
      "regex": "^[@]",
      "orderLevel": 10
    },
    {
      "regex": "^[^.@]",
      "orderLevel": 11
    },
    {
      "regex": "^[.]",
      "orderLevel": 30
    }
  ],
  "importSorter.sortConfiguration.removeUnusedImports": true,
"material-icon-theme.folders.theme": "none",
"workbench.iconTheme": "material-icon-theme",
"material-icon-theme.activeIconPack": "angular",
"material-icon-theme.opacity": 1,
"material-icon-theme.saturation": 0.7,

⚠️ This extension can be replaced by builtin inlay hints since version 1.60 + TypeScript 4.4.

ℹ️ This extension bundle is not optimized (quite heavy), but can help on projects where prettier is not used and some team members use IDEA IDE to have the same alignment behavior.

ℹ️ This extension works well, but if you use a multi-root workspace all the folders are scanned and a relative import will be privileged instead of a module import (import xxx from ../../../../../../ instead of import xxx from @company/toolkit). We should fork and update the source code of the application in order to use the paths defined in tsconfig file. In the meantime, we can modify the TypeScriptImporter.js file located in ~/.vscode/extensions/pmneo.tsimporter-2.0.1/out/TypeScriptImporter.js

if (lowImportance) {
    //NOTE: Fred - Adapt the code in order to have the modules listed before the paths (modules ordered from longest to shortest)
    // prefix:<symbolType>:<symbolLength>:symbolName (<symbolType>: 0 for module, 1 for path; <symbolLength>: 3 digits - the lower matches the longest modules, 999 for paths)
    let prefix = "zzzzzzzzzz";
    if (m.module) {
        let weight = 1000 - m.module.length;
        if (m.module.indexOf(".") > -1) {
            weight = weight + 100;  // we prefer the imports from the parent folder
            weight = weight > 1000 ? 999 : weight
        }
        prefix = prefix + ":0:" + String(weight).padStart(3, '0') + ":";
    } else {
        prefix = prefix + ":1:999:";
    }
    
    this.sortText = prefix + m.name;
    this.label = m.name;
    this.insertText = m.name;
}

Snippets

Angular

⚠️ Some Selectors (angular components) are not detected

⚠️ Seems to work better than Angular Follow Selector, but the memory usage is very high

ℹ️ This extension will use the angular.json configuration file to customize its behaviour. If the project doesn't have one, you could use the following sample

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "defaultProject": "my-proj",
  "projects": {
    "my-proj": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "style": "css",
          "spec": false,
          "flat": true
        },
        "@schematics/angular:service": {
          "spec": false,
          "flat": true
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "my-proj",
    }
  }
}

Database

Git

Markdown

Vi

  • VSCodeVim

    This extension can be configured in settings:

      "vim.hlsearch": true,
      "vim.sneak": true,
      "workbench.list.keyboardNavigation": "filter",
      "vim.leader": "<Space>",
      "vim.easymotion": true,
      "vim.changeWordIncludesWhitespace": true,
      "vim.sneakReplacesF": true,
      "vim.sneakUseIgnorecaseAndSmartcase": true,
      "vim.useSystemClipboard": true,
      "vim.replaceWithRegister": true,
      "vim.useCtrlKeys": false,
      "vim.normalModeKeyBindingsNonRecursive": [
      {
        "before": ["<Leader>", "/"],
        "commands": [":noh"]
      }]
    
    • keybindings
    {
      "key": "escape",
      "command": "-extension.vim_escape",
      "when": "editorTextFocus && vim.active && !inDebugRepl"
    },
    {
      "key": "escape",
      "command": "extension.vim_escape",
      "when": "editorTextFocus && !inDebugRepl && !suggestWidgetVisible"
    }
    

Utility tools

Productivity

Note taking (PKM)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment