Visual Studio Javascript



VSCode extension to integrate JavaScript Standard Style into VSCode. We support JavaScript Semi-Standard Style too, if you prefer keeping the semicolon. JavaScript Standard Style with custom tweaks. There are some extension in Visual Studio Code that is useful for web and app development using JavaScript, HTML, and CSS. This pack include extensions, git tools, todo list tools, recommended selection of themes and icons, and some utilities that useful in web development using JavaScript in front end stack or backend stack with Node JS. Defaults to 'javascript', 'javascriptreact'. Eslint.format.enable: enables ESLint as a formatter for validated files. Although you can also use the formatter on save using the setting editor.formatOnSave it is recommended to use the editor.codeActionsOnSave feature since it allows for better configurability.

Integrates ESLint into VS Code. If you are new to ESLint check the documentation.

The extension uses the ESLint library installed in the opened workspace folder. If the folder doesn't provide one the extension looks for a global install version. If you haven't installed ESLint either locally or globally do so by running npm install eslint in the workspace folder for a local install or npm install -g eslint for a global install.

On new folders you might also need to create a .eslintrc configuration file. You can do this by either using the VS Code command Create ESLint configuration or by running the eslint command in a terminal. If you have installed ESLint globally (see above) then run eslint --init in a terminal. If you have installed ESLint locally then run .node_modules.bineslint --init under Windows and ./node_modules/.bin/eslint --init under Linux and Mac.

Release Notes

This section describes major releases and their improvements. For a detailed list of changes please refer to the change log;

Version 2.1.20

Added support to customize the severity of eslint rules. See the new setting eslint.rules.customizations.

Version 2.1.18

Asking for confirmation of the eslint.nodePath value revealed a setup where that value is defined separately on a workspace folder level although a multi workspace folder setup is open (e.g. a code-workspace file). These setups need to define the eslint.nodePath value in the corresponding code-workspace file and the extension now warns the user about it. Below an example of such a code-workspace file

Version 2.1.17

Javascript

To follow VS Code's model to confirm workspace local settings that impact code execution the two settings eslint.runtime and eslint.nodePath now need user confirmation if defined locally in a workspace folder or a workspace file. Users using these settings in those local scopes will see a notification reminding them of the confirmation need.

The version also adds a command to restart the ESLint server.

Version 2.1.10

The approval flow to allow the execution of a ESLint library got reworked. Its initial experience is now as follows:

  • no modal dialog is shown when the ESLint extension tries to load an ESLint library for the first time and an approval is necessary. Instead the ESLint status bar item changes to indicating that the execution is currently block.
  • if the active text editor content would be validated using ESLint, a problem at the top of the file is shown in addition.

The execution of the ESLint library can be denied or approved using the following gestures:

  • clicking on the status bar icon
  • using the quick fix for the corresponding ESLint problem
  • executing the command ESLint: Manage Library Execution from the command palette

All gestures will open the following dialog:

The chosen action is then reflected in the ESLint status bar item in the following way:

  • Allow will prefix the status bar item with a check mark.
  • Allow Everywhere will prefix the status bar item with a double check mark.
  • Deny and Disable will prefix the status bar item with a blocked sign.

You can manage our decisions using the following commands:

  • ESLint: Manage Library Execution will reopen aboves dialog
  • ESLint: Reset Library Decisions lets you reset previous decisions who have made.

This release also addresses the vulnerability described in CVE-2021-27081.

Version 2.0.4

The 2.0.4 version of the extension contains the following major improvements:

  • Improved TypeScript detection - As soon as TypeScript is correctly configured inside ESLint, you no longer need additional configuration through VS Code's eslint.validate setting. The same is true for HTML and Vue.js files.
  • Glob working directory support - Projects that have a complex folder structure and need to customize the working directories via eslint.workingDirectories can now use glob patterns instead of listing every project folder. For example, { 'pattern': 'code-*' } will match all project folders starting with code-. In addition, the extension now changes the working directory by default. You can disable this feature with the new !cwd property.
  • Formatter support: ESLint can now be used as a formatter. To enable this feature use the eslint.format.enable setting.
  • Improved Auto Fix on Save - Auto Fix on Save is now part of VS Code's Code Action on Save infrastructure and computes all possible fixes in one round. It is customized via the editor.codeActionsOnSave setting. The setting supports the ESLint specific property source.fixAll.eslint. The extension also respects the generic property source.fixAll.

The setting below turns on Auto Fix for all providers including ESLint:

In contrast, this configuration only turns it on for ESLint:

You can also selectively disable ESLint via:

Also note that there is a time budget of 750ms to run code actions on save which might not be enough for large JavaScript / TypeScript file. You can increase the time budget using the editor.codeActionsOnSaveTimeout setting.

The old eslint.autoFixOnSave setting is now deprecated and can safely be removed.

Settings Options

Visual Studio Javascript Web

If you are using an ESLint extension version < 2.x then please refer to the settings options here.

This extension contributes the following variables to the settings:

  • eslint.enable: enable/disable ESLint. Is enabled by default. This setting got deprecated in favour of enabling / disabling the extension in the Extension's viewlet.

  • eslint.debug: enables ESLint's debug mode (same as --debug command line option). Please see the ESLint output channel for the debug output. This options is very helpful to track down configuration and installation problems with ESLint since it provides verbose information about how ESLint is validating a file.

  • eslint.lintTask.enable: whether the extension contributes a lint task to lint a whole workspace folder.

  • eslint.lintTask.options: Command line options applied when running the task for linting the whole workspace (https://eslint.org/docs/user-guide/command-line-interface).An example to point to a custom .eslintrc.json file and a custom .eslintignore is:

  • eslint.packageManager: controls the package manager to be used to resolve the ESLint library. This has only an influence if the ESLint library is resolved globally. Valid values are 'npm' or 'yarn' or 'pnpm'.

  • eslint.options: options to configure how ESLint is started using the ESLint CLI Engine API. Defaults to an empty option bag.An example to point to a custom .eslintrc.json file is:

  • eslint.run - run the linter onSave or onType, default is onType.

  • eslint.quiet - ignore warnings.

  • eslint.runtime - use this setting to set the path of the node runtime to run ESLint under.

  • eslint.nodeEnv - use this setting if an ESLint plugin or configuration needs process.env.NODE_ENV to be defined.

  • eslint.nodePath - use this setting if an installed ESLint package can't be detected, for example /myGlobalNodePackages/node_modules.

  • eslint.probe = an array for language identifiers for which the ESLint extension should be activated and should try to validate the file. If validation fails for probed languages the extension says silent. Defaults to ['javascript', 'javascriptreact', 'typescript', 'typescriptreact', 'html', 'vue', 'markdown'].

  • eslint.validate - an array of language identifiers specifying the files for which validation is to be enforced. This is an old legacy setting and should in normal cases not be necessary anymore. Defaults to ['javascript', 'javascriptreact'].

  • eslint.format.enable: enables ESLint as a formatter for validated files. Although you can also use the formatter on save using the setting editor.formatOnSave it is recommended to use the editor.codeActionsOnSave feature since it allows for better configurability.

  • eslint.workingDirectories - specifies how the working directories ESLint is using are computed. ESLint resolves configuration files (e.g. eslintrc, .eslintignore) relative to a working directory so it is important to configure this correctly. If executing ESLint in the terminal requires you to change the working directory in the terminal into a sub folder then it is usually necessary to tweak this setting. (see also CLIEngine options#cwd). Please also keep in mind that the .eslintrc* file is resolved considering the parent directories whereas the .eslintignore file is only honored in the current working directory. The following values can be used:

    • [{ 'mode': 'location' }] (@since 2.0.0): instructs ESLint to uses the workspace folder location or the file location (if no workspace folder is open) as the working directory. This is the default and is the same strategy as used in older versions of the ESLint extension (1.9.x versions).
    • [{ 'mode': 'auto' }] (@since 2.0.0): instructs ESLint to infer a working directory based on the location of package.json, .eslintignore and .eslintrc* files. This might work in many cases but can lead to unexpected results as well.
    • string[]: an array of working directories to use.Consider the following directory layout:Then using the setting:will validate files inside the server directory with the server directory as the current eslint working directory. Same for files in the client directory. The ESLint extension will also change the process's working directory to the provided directories. If this is not wanted a literal with the !cwd property can be used (e.g. { 'directory': './client', '!cwd': true }). This will use the client directory as the ESLint working directory but will not change the process`s working directory.
    • [{ 'pattern': glob pattern }] (@since 2.0.0): Allows to specify a pattern to detect the working directory. This is basically a short cut for listing every directory. If you have a mono repository with all your projects being below a packages folder you can use { 'pattern': './packages/*/' } to make all these folders working directories.
  • eslint.codeAction.disableRuleComment - object with properties:

    • enable - show disable lint rule in the quick fix menu. true by default.
    • location - choose to either add the eslint-disable comment on the separateLine or sameLine. separateLine is the default.Example:
  • eslint.codeAction.showDocumentation - object with properties:

    • enable - show open lint rule documentation web page in the quick fix menu. true by default.
  • eslint.codeActionsOnSave.mode (@since 2.0.12): controls which problems are fix when running code actions on save

    • all: fixes all possible problems by revalidating the file's content. This executes the same code path as running eslint with the --fix option in the terminal and therefore can take some time. This is the default value.
    • problems: fixes only the currently known fixable problems as long as their textual edits are non overlapping. This mode is a lot faster but very likely only fixes parts of the problems.
  • eslint.rules.customizations (@since 2.1.20): force rules to report a different severity within VS Code compared to the project's true ESLint configuration. Contains two properties:

    • 'rule': Select on rules with names that match, factoring in asterisks as wildcards: { 'rule': 'no-*', 'severity': 'warn' }
      • Prefix the name with a '!' to target all rules that don't match the name: { 'rule': '!no-*', 'severity': 'info' }
    • 'severity': Sets a new severity for matched rule(s), 'downgrade's them to a lower severity, 'upgrade's them to a higher severity, or 'default's them to their original severity

    In this example, all rules are overridden to warnings:

    In this example, no- rules are informative, other rules are downgraded, and 'radix' is reset to default:

  • eslint.format.enable (@since 2.0.0): uses ESlint as a formatter for files that are validated by ESLint. If enabled please ensure to disable other formatters if you want to make this the default. A good way to do so is to add the following setting '[javascript]': { 'editor.defaultFormatter': 'dbaeumer.vscode-eslint' } for JavaScript. For TypeScript you need to add '[typescript]': { 'editor.defaultFormatter': 'dbaeumer.vscode-eslint' }.

  • eslint.onIgnoredFiles (@since 2.0.10): used to control whether warnings should be generated when trying to lint ignored files. Default is off. Can be set to warn.

  • editor.codeActionsOnSave (@since 2.0.0): this setting now supports an entry source.fixAll.eslint. If set to true all auto-fixable ESLint errors from all plugins will be fixed on save. You can also selectively enable and disabled specific languages using VS Code's language scoped settings. To disable codeActionsOnSave for HTML files use the following setting:

The old eslint.autoFixOnSave setting is now deprecated and can safely be removed. Please also note that if you use ESLint as your default formatter you should turn off editor.formatOnSave when you have turned on editor.codeActionsOnSave. Otherwise you file gets fixed twice which in unnecessary.

Settings Migration

If the old eslint.autoFixOnSave option is set to true ESLint will prompt to convert it to the new editor.codeActionsOnSave format. If you want to avoid the migration you can respond in the dialog in the following ways:

  • Not now: the setting will not be migrated by ESLint prompts again the next time you open the workspace
  • Never migrate Settings: the settings migration will be disabled by changing the user setting eslint.migration.2_x to off

The migration can always be triggered manually using the command ESLint: Migrate Settings

Commands:

This extension contributes the following commands to the Command palette.

  • Create '.eslintrc.json' file: creates a new .eslintrc.json file.
  • Fix all auto-fixable problems: applies ESLint auto-fix resolutions to all fixable problems.
  • Reset Library Decisions: Resets the ESLint library validation confirmations.
  • Manage Library Execution: Opens the library execution confirmation dialog.

Using the extension with VS Code's task running

The extension is linting an individual file only on typing. If you want to lint the whole workspace set eslint.lintTask.enable to true and the extension will also contribute the eslint: lint whole folder task. There is no need anymore to define a custom task in tasks.json.

Using ESLint to validate TypeScript files

A great introduction on how to lint TypeScript using ESlint can be found in the TypeScript - ESLint. Please make yourself familiar with the introduction before using the VS Code ESLint extension in a TypeScript setup. Especially make sure that you can validate TypeScript files successfully in a terminal using the eslint command.

This project itself uses ESLint to validate its TypeScript files. So it can be used as a blueprint to get started.

To avoid validation from any TSLint installation disable TSLint using 'tslint.enable': false.

Mono repository setup

As with JavaScript validating TypeScript in a mono repository requires that you tell the VS Code ESLint extension what the current working directories are. Use the eslint.workingDirectories setting to do so. For this repository the working directory setup looks as follows:

ESLint 6.x

Migrating from ESLint 5.x to ESLint 6.x might need some adaption (see the ESLint Migration Guide for details). Before filing an issue against the VS Code ESLint extension please ensure that you can successfully validate your files in a terminal using the eslint command.

This topic describes some of the advanced JavaScript features supported by Visual Studio Code. Using the TypeScript language service, VS Code can provide smart completions (IntelliSense) as well as type checking for JavaScript.

IntelliSense

Visual Studio Code's JavaScript IntelliSense provides intelligent code completion, parameter info, references search, and many other advanced language features. Our JavaScript IntelliSense is powered by the JavaScript language service developed by the TypeScript team. While IntelliSense should just work for most JavaScript projects without any configuration, you can make IntelliSense even more useful with JSDoc or by configuring a jsconfig.json project.

For the details of how JavaScript IntelliSense works, including being based on type inference, JSDoc annotations, TypeScript declarations, and mixing JavaScript and TypeScript projects, see the JavaScript language service documentation.

When type inference does not provide the desired information, type information may be provided explicitly with JSDoc annotations. This document describes the JSDoc annotations currently supported.

In addition to objects, methods, and properties, the JavaScript IntelliSense window also provides basic word completion for the symbols in your file.

Typings and Automatic Type Acquisition

IntelliSense for JavaScript libraries and frameworks is powered by TypeScript type declaration (typings) files. Type declaration files are written in TypeScript so they can express the data types of parameters and functions, allowing VS Code to provide a rich IntelliSense experience in a performant manner.

Many popular libraries ship with typings files so you get IntelliSense for them automatically. For libraries that do not include typings, VS Code's Automatic Type Acquisition will automatically install community maintained typings file for you.

Automatic type acquisition requires npmjs, the Node.js package manager, which is included with the Node.js runtime. In this image you can see IntelliSense, including the method signature, parameter info, and the method's documentation for the popular lodash library.

Type declaration files are automatically downloaded and managed by Visual Studio Code for packages listed in your project's package.json or that you import into a JavaScript file.

You can alternately explicitly list packages to acquire type declaration files for in a jsconfig.json.

Most common JavaScript libraries ship with declaration files or have type declaration files available. You can search for a library's type declaration file package using the TypeSearch site.

Fixing npm not installed warning for Automatic Type Acquisition

Automatic Type Acquisition uses npm, the Node.js package manager, to install and manage Type Declaration (typings) files. To ensure that Automatic Type Acquisition works properly, first ensure that you have npm installed on your machine.

Run npm --version from a terminal or command prompt to quickly check that npm is installed and available.

npm is installed with the Node.js runtime, which is available for download from Nodejs.org. Install the current LTS (Long Term Support) version and the npm executable will be added by default to your system path.

If you have npm installed but still see a warning message, you can explicitly tell VS Code where npm is installed with the typescript.npmsetting. This should be set to the full path of the npm executable on your machine, and this does not have to match the version of npm you are using to manage packages in your workspace. typescript.npm requires TypeScript 2.3.4+.

For example, on Windows, you would add a path like this to your settings.json file:

JavaScript projects (jsconfig.json)

Hello

The presence of a jsconfig.json file in a directory indicates that the directory is the root of a JavaScript project. jsconfig.json specifies the root files and the options for the language features provided by the JavaScript language service. For common setups, a jsconfig.json file is not required, however, there are situations when you will want to add a jsconfig.json.

  • Not all files should be in your JavaScript project (for example, you want to exclude some files from showing IntelliSense). This situation is common with front-end and back-end code.
  • Your workspace contains more than one project context. In this situation, you should add a jsconfig.json file at the root folder for each project.
  • You are using the TypeScript compiler to down-level compile JavaScript source code.

Location of jsconfig.json

To define our code as a JavaScript project, create jsconfig.json at the root of your JavaScript code as shown below. A JavaScript project is the source files of the project and should not include the derived or packaged files (such as a dist directory).

In more complex projects, you may have more than one jsconfig.json file defined inside a workspace. You will want to do this so that the source code in one project does not appear in the IntelliSense of another project.

Illustrated below is a project with a client and server folder, showing two separate JavaScript projects:

Writing jsconfig.json

Below is a simple template for jsconfig.json file, which defines the JavaScript target to be ES6 and the exclude attribute excludes the node_modules folder. You can copy and paste this code into your jsconfig.json file.

The exclude attribute tells the language service which files are not part of your source code. If IntelliSense is slow, add folders to your exclude list (VS Code will prompt you to do this if it detects slow completions). You will want to exclude files generated by a build process (such as a dist directory). These files will cause suggestions to show up twice and will slow down IntelliSense.

You can explicitly set the files in your project using the include attribute. If no include attribute is present, then this defaults to including all files in the containing directory and subdirectories. When a include attribute is specified, only those files are included.

Here is an example with an explicit include attribute:

The best practice, and least error prone route, is to use the include attribute with a single src folder. Note that file paths in exclude and include are relative to the location of jsconfig.json.

For more information, see the full jsconfig.json documentation.

Migrating to TypeScript

It is possible to have mixed TypeScript and JavaScript projects. To start migrating to TypeScript, rename your jsconfig.json file to tsconfig.json and set the allowJs property to true. For more information, see Migrating from JavaScript.

Note:jsconfig.json is the same as a tsconfig.json file, only with allowJs set to true. See the documentation for tsconfig.json here to see other available options.

Type checking JavaScript

VS Code allows you to leverage some of TypeScript's advanced type checking and error reporting functionality in regular JavaScript files. This is a great way to catch common programming mistakes. These type checks also enable some exciting Quick Fixes for JavaScript, including Add missing import and Add missing property.

TypeScript can infer types in .js files same as in .ts files. When types cannot be inferred, they can be specified using JSDoc comments. You can read more about how TypeScript uses JSDoc for JavaScript type checking in Type Checking JavaScript Files.

Type checking of JavaScript is optional and opt-in. Existing JavaScript validation tools such as ESLint can be used alongside the new built-in type checking functionality.

You can get started with type checking a few different ways depending on your needs.

Per file

Highlighting

Visual Studio Javascript Hello World

The easiest way to enable type checking in a JavaScript file is by adding // @ts-check to the top of a file.

Using // @ts-check is a good approach if you just want to try type checking in a few files but not yet enable it for an entire codebase.

Using a setting

To enable type checking for all JavaScript files without changing any code, just add 'js/ts.implicitProjectConfig.checkJs': true to your workspace or user settings. This enables type checking for any JavaScript file that is not part of a jsconfig.json or tsconfig.json project.

You can opt individual files out of type checking with a // @ts-nocheck comment at the top of the file:

You can also disable individual errors in a JavaScript file using a // @ts-ignore comment on the line before the error:

Using jsconfig or tsconfig

To enable type checking for JavaScript files that are part of a jsconfig.json or tsconfig.json, add 'checkJs': true to the project's compiler options:

jsconfig.json:

tsconfig.json:

This enables type checking for all JavaScript files in the project. You can use // @ts-nocheck to disable type checking per file.

JavaScript type checking requires TypeScript 2.3. If you are unsure what version of TypeScript is currently active in your workspace, run the TypeScript: Select TypeScript Version command to check. You must have a .js/.ts file open in the editor to run this command. If you open a TypeScript file, the version appears in the lower right corner.

Global variables and type checking

Let's say that you are working in legacy JavaScript code that uses global variables or non-standard DOM APIs:

If you try to use // @ts-check with the above code, you'll see a number of errors about the use of global variables:

  1. Line 2 - Property 'webkitNotifications' does not exist on type 'Window'.
  2. Line 2 - Cannot find name 'CAN_NOTIFY'.
  3. Line 3 - Property 'webkitNotifications' does not exist on type 'Window'.

If you want to continue using // @ts-check but are confident that these are not actual issues with your application, you have to let TypeScript know about these global variables.

To start, create a jsconfig.json at the root of your project:

Then reload VS Code to make sure the change is applied. The presence of a jsconfig.json lets TypeScript know that your Javascript files are part of a larger project.

Now create a globals.d.ts file somewhere your workspace:

d.ts files are type declarations. In this case, globals.d.ts lets TypeScript know that a global CAN_NOTIFY exists and that a webkitNotifications property exists on window. You can read more about writing d.ts in the TypeScript documentation. d.ts files do not change how JavaScript is evaluated, they are used only for providing better JavaScript language support.

Using tasks

Using the TypeScript compiler

One of the key features of TypeScript is the ability to use the latest JavaScript language features, and emit code that can execute in JavaScript runtimes that don't yet understand those newer features. With JavaScript using the same language service, it too can now take advantage of this same feature.

Visual studio javascript intellisense

The TypeScript compiler tsc can down-level compile JavaScript files from ES6 to another language level. Configure the jsconfig.json with the desired options and then use the –p argument to make tsc use your jsconfig.json file, for example tsc -p jsconfig.json to down-level compile.

Read more about the compiler options for down level compilation in the jsconfig documentation.

Running Babel

The Babel transpiler turns ES6 files into readable ES5 JavaScript with Source Maps. You can easily integrate Babel into your workflow by adding the configuration below to your tasks.json file (located under the workspace's .vscode folder). The group setting makes this task the default Task: Run Build Task gesture. isBackground tells VS Code to keep running this task in the background. To learn more, go to Tasks.

Once you have added this, you can start Babel with the ⇧⌘B (Windows, Linux Ctrl+Shift+B) (Run Build Task) command and it will compile all files from the src directory into the lib directory.

Tip: For help with Babel CLI, see the instructions in Using Babel. The example above uses the CLI option.

Disable JavaScript support

If you prefer to use JavaScript language features supported by other JavaScript language tools such as Flow, you can disable VS Code's built-in JavaScript support. You do this by disabling the built-in TypeScript language extension TypeScript and JavaScript Language Features (vscode.typescript-language-features) which also provides the JavaScript language support.

To disable JavaScript/TypeScript support, go to the Extensions view (⇧⌘X (Windows, Linux Ctrl+Shift+X)) and filter on built-in extensions (Show Built-in Extensions in the ...More Actions dropdown), then type 'typescript'. Select the TypeScript and JavaScript Language Features extension and press the Disable button. VS Code built-in extensions cannot be uninstalled, only disabled, and can be re-enabled at any time.





Comments are closed.