Visual Studio Code Javascript



-->

  1. Visual Studio Code Javascript Run
  2. Visual Studio Code Javascript Debug

In this video, our expert mentor, two-time GSoC participant, and a GSoC mentor, Arnav Gupta explains some of the various useful extensions which can be used. This video shows you how to setup Visual Studio Code for Javascript Development 2018 and will be the prelude to the extensive Javascript tutorial I will be s. Visual Studio provides an out of the box, first class debugging experience for JavaScript. Powerful features like source maps allow you to drop breakpoints directly in your code. Performance profilers make finding runtime memory bottlenecks trivial. Visual Studio Code Get started with web development by learning how to use HTML, CSS, and JavaScript to build a website, use developer tools in the browser to check your work.

You can use commands to send messages and perform other tasks in the JavaScript Console window of Visual Studio. For examples that show how to use this window, see QuickStart: Debug JavaScript. The information in this topic applies to Node.js app, UWP apps, and apps created using Visual Studio Tools for Apache Cordova.

If the JavaScript Console window is closed, you can open it while you're debugging in Visual Studio by choosing Debug > Windows > JavaScript Console.

Note

If the window is not available during a debugging session, make sure that the debugger type is set to Script in the Debug properties for the project.

For info on using the console in Microsoft Edge Developer tools, see this topic.

console object commands

This table shows the syntax for the console object commands that you can use in the JavaScript Console window, or that you can use to send messages to the console from your code. This object provides a number of forms so that you can distinguish between informational messages and error messages, if you want to.

You can use the longer command form window.console.[command] if you need to avoid possible confusion with local objects named console.

Tip

Older versions of Visual Studio do not support the complete set of commands. Use IntelliSense on the console object to get quick information about supported commands.

CommandDescriptionExample
assert(expression, message)Sends a message if expression evaluates to false.console.assert((x 1), 'assert message: x != 1');
clear()Clears messages from the console window, including script-error messages, and also clears script that appears in the console window. Does not clear script that you entered into the console input prompt.console.clear();
count(title)Sends the number of times that the count command was called to the console window. Each call to count is uniquely identified by the optional title.
The existing entry in the console window is identified by the title parameter (if present) and updated by the count command. A new entry is not created.
console.count();
console.count('inner loop');
debug(message)Sends message to the console window.
This command is identical to console.log.
Objects that are passed by using the command are converted to a string value.
console.debug('logging message');
dir(object)Sends the specified object to the console window and displays it in an object visualizer. You can use the visualizer to inspect properties in the console window.console.dir(obj);
dirxml(object)Sends the specified XML node object to the console window and displays it as an XML node tree.console.dirxaml(xmlNode);
error(message)Sends message to the console window. The message text is red and prefaced by an error symbol.
Objects that are passed by using the command are converted to a string value.
console.error('error message');
group(title)Starts a grouping for messages that are sent to the console window, and sends the optional title as a group label. Groups can be nested and appear in a tree view in the console window.
The group* commands can make it easier to view console window output in some scenarios, such as when a component model is in use.
console.group('Level 2 Header');
console.log('Level 2');
console.group();
console.log('Level 3');
console.warn('More of level 3');
console.groupEnd();
console.log('Back to level 2');
console.groupEnd();
console.debug('Back to the outer level');
groupCollapsed(title)Starts a grouping for messages that are sent to the console window, and sends the optional title as a group label. Groups that are sent by using groupCollapsed appear in a collapsed view by default. Groups can be nested and appear in a tree view in the console window.Usage is the same as the group command.
See the example for the group command.
groupEnd()Ends the current group.
Requirements:
Visual Studio 2013
See the example for the group command.
info(message)Sends message to the console window. The message is prefaced by an information symbol.console.info('info message');
For more examples, see Formatting console.log output later in this topic.
log(message)Sends message to the console window.
If you pass an object, this command sends that object to the console window and displays it in an object visualizer. You can use the visualizer to inspect properties in the console window.
console.log('logging message');
msIsIndependentlyComposed(element)Used in web apps. Not supported in UWP apps using JavaScript.Not supported.
profile(reportName)Used in web apps. Not supported in UWP apps using JavaScript.Not supported.
profileEnd()Used in web apps. Not supported in UWP apps using JavaScript.Not supported.
select(element)Selects the specified HTML element in the DOM Explorer.console.select(element);
time (name)Starts a timer that's identified by the optional name parameter. When used with console.timeEnd, calculates the time that elapses between time and timeEnd, and sends the result (measured in ms) to the console using the name string as a prefix. Used to enable instrumentation of app code for measuring performance.console.time('app start'); app.start(); console.timeEnd('app start');
timeEnd(name)Stops a timer that's identified by the optional name parameter. See the time console command.console.time('app start'); app.start(); console.timeEnd('app start');
trace()Sends a stack trace to the console window. The trace includes the complete call stack, and includes info such as filename, line number, and column number.console.trace();
warn(message)Sends message to the console window, prefaced by a warning symbol.
Objects that are passed by using the command are converted to a string value.
console.warn('warning message');

Miscellaneous commands

These commands are also available in the JavaScript Console window (they are not available from code).

CommandDescriptionExample
$0, $1, $2, $3, $4Returns the specified element to the console window. $0 returns the element currently selected in DOM Explorer, $1 returns the element previously selected in DOM Explorer, and so on, up to the fourth previously selected element.$3
$(id)Returns an element by ID. This is a shortcut command for document.getElementById(id), where id is a string that represents the element ID.$('contenthost')
$$(selector)Returns an array of elements that match the specified selector using CSS selector syntax. This is a shortcut command for document.querySelectorAll().$$('.itemlist')
cd()
cd(window)
Enables you to change the context for expression evaluation from the default top-level window of the page to the window of the specified frame. Calling cd() without parameters returns the context to the top-level window.cd();
cd(myframe);
select(element)Selects the specified element in DOM Explorer.select(document.getElementById('element'));
select($('element'));
select($1);
dir(object)Returns a visualizer for the specified object. You can use the visualizer to inspect properties in the console window.dir(obj);

Checking whether a console command exists

You can check whether a specific command exists before attempting to use it. This example checks for the existence of the console.log command. If console.log exists, the code calls it.

Examining objects in the JavaScript Console window

You can interact with any object that's in scope when you use the JavaScript Console window. To inspect an out-of-scope object in the console window, use console.log , console.dir, or other commands from your code. Alternatively, you can interact with the object from the console window while it is in scope by setting a breakpoint in your code (Breakpoint > Insert Breakpoint).

Formatting console.log output

Visual Studio Code Javascript

If you pass multiple arguments to console.log, the console will treat the arguments as an array and concatenate the output.

console.log also supports 'printf' substitution patterns to format output. If you use substitution patterns in the first argument, additional arguments will be used to replace the specified patterns in the order they are used.

The following substitution patterns are supported:

  • %s - string%i - integer%d - integer%f - float%o - object%b - binary%x - hexadecimal%e - exponent

    Here are some examples of using substitution patterns in console.log:

See also

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

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

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

Visual Studio Code Javascript Run

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:

Visual studio

ESLint 6.x

Visual Studio Code Javascript Debug

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.





Comments are closed.