Работа на языке JavaScript в Visual Studio Code
Мы возьмем VS Code как редактор для разработки на JavaScript (в частности React и ReactNative , так как платформа выглядит мощной и популярной). Вообще если отвлечься от конкретного языка VS Code это качественный текстовый редактор с огромными возможностями и потенциалом к расширению. Существует множество различных инструментов и плагинов, призванных помочь нам в работе. Попробуем их обуздать.
Редактор бесплатный, его можно скачать с официального сайта, там же можно найти документацию, FAQ, расширения и многое другое. Сообщество пользователей очень велико. Редактор является программным обеспечением с открытым исходным кодом и большинство расширений к нему — тоже. Это значит, что теоретически любой разработчик может принять участие в разработке самого инструмента.
Сам редактор приятен в пользовании как визуально, так и в плане удобства.
Create New
Следите за руками. Открываем VS Code, сочетание клавиш Ctrl+N создает новый файл (пока просто текстовый) хорошо, жамкаем Ctrl+K,M (такое сочетание означает, что надо сначала зажать вместе клавиши Ctrl и K, а затем отпустить их и нажать клавишу M), и выбираем язык на котором будем писать, редактор соответственно постарается помочь нам подсветкой и чем еще сможет. Начинаем набирать func, срабатывает автодополнение (это часть технологии IntelliSense) до function (применяется через Tab или Enter). Автодополнение позволяет значительно меньше набирать и снижает количество ошибок.
ES Lint
Пока все идет хорошо. Но, JS знаменит тем, что на нем можно в редакторе творить жуткое, а ошибки ловить только при запуске и потом долго и с наслаждением их искать (привет динамическая типизация). Есть плагин ESLint, который по сути просто использует одноименный инструмент. Linting — это проверка соблюдения стандарта оформления кода. ES — это язык ECMA Script стандартизированный международной организацией ECMA в спецификации ECMA-262, расширением которого и является JS. По сути плагин проверяет, что написанное нами соответствует стандарту языка, но мы можем настраивать эту проверку.
Это первый плагин, который мы поставим. Есть 2 способа сделать это. Во-первых, есть онлайн магазин расширений для VSCode, воспользовавшись поиском можно найти любой требуемый плагин и нажать кнопочку install . Но зачем куда-то ходить, marketplace есть прямо в редакторе!
Если нажать сочетание клавиш Ctrl+Shift+X или кнопку на панели слева, откроется панель поиска расширений. Можно ввести в строке поиска ‘ESLint’, нажать на иконку плагина в списке результатов и тогда откроется домашняя страничка этого плагина с исчерпывающей информацией о нем. Здесь, для установки также следует нажать кнопочку install .
Плагин есть, но нет той библиотеки, которую он использует. Тут нам надо познакомиться с еще одним источником инструментов для разработки на JS. Наверно, тут не место отвлекаться на тему, что такое сторонний код, библиотеки и пакетные менеджеры. В сообществе JS, если вы хотите использовать кем-то написанный код (а на JS вам буквально придется это делать), вы можете использовать npm. Тут отдельная статья как эту штуку установить.
Теперь когда у нас есть npm можем ставить пакеты!
Опция -g говорит пакетному менеджеру поставить пакет не в какой-то конкретный проект, а глобально.
А это плагины, которые конфигурируют eslint. Без них (по умолчанию) eslint ничего не проверяет. (будем следовать Airbnb code style)
Это конфиг который должен лежать в папке нашего проекта .eslintrc.json:
В принципе его можно создать при помощи мастера настройки по команде
Можно вообще положить конфиг в папку %UserName% и VSCode будет читать оттуда. Подробное описание конфигурации и всех правил можно найти на официальном сайте
Prettier
Еще очень хочется не парится насчет пробелов, табов, переносов, скобок и такого прочего, писать себе подряд и, если что-то пошло вразнобой, автоматом поправить с помощью какого-то инструмента. В принципе, ES Lint частично уже делает это за нас, но с Prettier как-то побаче.
Ставим одноименный плагин, в настройках выставляем галку prettier.eslintIntegration, чтобы линтер с форматером не воевали, чей стиль лучше. Если редактор вдруг не спросит какой форматер использовать по умолчанию для JS, указываем
С этого момента можно считать, что мы прикрутили боковые колеса, которые заботливо не будут давать нам упасть.
Personal Access Token
Буду исходить из предположения, что аккаунт на GitHub у Вас есть. Теперь нужно завести токен. Идем в Settings → Developer Settings → Personal Access Tokens. Обзываем понятным образом и обязательно ставим галочку gist .

Нажимаем Generate и далее обязательно копируем его куда-нибудь, больше нам этот токен не покажут.

Settings Sync Extension
Ставим одноименное расширение для VS Code. Время залить свои первые настройки! Ctrl+Shift+P Вызывает командную консоль, в ней можем набрать >Sync и выбрать команду Upload (либо Shift + Alt + U прямо из редактора). При первом вызове расширение попросит ввести token, который мы заботливо сохранили на предыдущем шаге. А при успешной загрузке настроек вернет GistID, который тоже надо сохранить, чтобы иметь возможность скачать эти настройки на другой машине.
Если ввести ссылку вида https://gist.github.com/
Можно поставить расширение Gist для VS Code и прямо из редактора загружать или скачивать различные файлы. В том числе можно сохранить свой файл .eslintrc.
Опциональные расширения
Auto Close Tag — автоматически добавляет закрывающий тэг
Auto Rename Tag — автоматически переименовывает парный тэг
Color highlight — подсветка шестнадцатеричных кодов цветов
Codestream — интересное расширение для совместной работы над кодом
GitLens — git аннотации
ToDo Tree — подсветка и навигация по меткам ToDo
А вообще вот поиск

ни в чем себе не отказывайте)
Gotcha.Blog
- Gotcha.Blog
Еще один блог программиста, что поделаешь. Этот блог сгенерирован при помощи Jekyll и хостится на Github pages.
Working with JavaScript
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.npm setting. 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)
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
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:
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:
- Line 2 — Property ‘webkitNotifications’ does not exist on type ‘Window’.
- Line 2 — Cannot find name ‘CAN_NOTIFY’.
- 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.
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.

Partial IntelliSense mode
VS Code tries to provide project-wide IntelliSense for JavaScript and TypeScript, which is what makes features such as auto-imports and Go to Definition possible. However, there are some cases where VS Code is limited to working only with your currently opened files and is unable to load the other files that make up your JavaScript or TypeScript project.
This can happen in a few instances:
- You are working with JavaScript or TypeScript code on vscode.dev or github.dev and VS Code is running in the browser.
- You open a file from a virtual file system (such as when using the GitHub Repositories extension).
- The project is currently loading. Once loading completes, you will start getting project-wide IntelliSense for it.
In these cases, VS Code’s IntelliSense will operate in partial mode. Partial mode tries its best to provide IntelliSense for any JavaScript or TypeScript files you have open, but is limited and is not able to offer any cross-file IntelliSense features.
Which features are impacted?
Here’s an incomplete list of features that are either disabled or have more limited functionality in partial mode:
- All opened files are treated as part of a single project.
- Configuration options from your jsconfig or tsconfig (such as target ) are not respected.
- Only syntax errors are reported. Semantic errors — such as accessing an unknown property or passing the wrong type to a function — are not reported.
- Quick Fixes for semantic errors are disabled.
- Symbols can only be resolved within the current file. Any symbols imported from other files will be treated as being of the any type.
- Commands such as Go to Definition and Find All References will only work for opened files instead of across the entire project. This also means that symbol from any packages you install under node_module will not be resolved.
- Workspace symbol search will only include symbols from currently opened files.
- Auto imports are disabled.
- Renaming is disabled.
- Many refactorings are disabled.
Some additional features are disabled on vscode.dev and github.dev :
-
is currently not supported.
Checking if you are in partial mode
To check if the current file is using partial mode IntelliSense instead of project-wide IntelliSense, hover over the JavaScript or TypeScript language status item in the status bar:

The status item will show Partial mode if the current file is in partial mode.
Как настроить VS Code для разработки на JavaScript

Visual Studio Code – популярный бесплатный редактор кода, созданный Microsoft'ом для программистов. VS Code никак не связан с Visual Studio. VS Code работает быстрее Атома, активно развивается и легко расширяется плагинами.
- отладчик кода
- встроенный терминал
- удобные инструменты для работы с Git
- подсветка синтаксиса для множества популярных языков и файловых форматов
- удобная навигация
- встроенный предпросмотр Markdown
- умное автодополнение
- встроенный пакетный менеджер
Пакетный менеджер нужен для установки и удаления пакетов расширений (плагинов). Для удобной разработки на JavaScript для бэкенда и фронтенда нужно установить несколько пакетов.

Для установки нового пакета зайдите в выпадающее меню "View" на вкладку "Extensions" и введите название пакета в строке поиска, а затем нажмите кнопку "Install".
Babel и ES6
VS Code содержит понятие "сборки проекта". Редактор можно настроить таким образом, чтобы сборка JavaScript-проекта заключалась в конвертации кода из ES6 в читаемый ES5 с Source Maps с помощью Babel.
Добавьте таск (задание) в файл tasks.json в директории .vscode в корне вашего проекта:
Теперь комбинация клавиш Shift+Ctrl+B (Windows/Linux) или Shift+CMD+B (macOS) запустит сборку.
Стандарты кодирования
Eslint – это утилита, проверяющая стандарты кодирования на JavaScript. Стандарт де-факто в мире JS.

Нужно сначала установить eslint в системе, а потом установить расширение VS Code, которое будет использовать установленный линтер. Есть разные способы интеграции линтера с расширением. Мы рассмотрим установку линтера глобально в системе.
Установите eslint командой npm install -g eslint . Вероятно, вам понадобится использовать sudo .
Установите плагины, которые конфигурируют eslint . Без них (по умолчанию) eslint ничего не проверяет.
eslint требует наличия конфигурационного файла. Создайте в корне вашего проекта файл .eslintrc.yml со следующим содержанием:
Установите расширение " linter-eslint" в VS Code.
Автоматическое дополнение
VS Code содержит мощную систему анализа кода для автодополнений и подсказок – IntelliSense.
IntelliSense работает сразу, но для настройки деталей нужно создать конфигурационный файл jsconfig.json .
jsconfig.json
Если положить в корень директории с JavaScript-проектом конфигурационный файл jsconfig.json , то VS Code будет использовать эту конфигурацию для работы с вашим проектом. Вот пример такого файла:
Здесь можно настроить, например, какие директории стоит исключить из системы автодополнений IntelliSense. VS Code совместим с node, webpack, bower, ember и другими популярными инструментами. Полная документация по jsconfig доступна на сайте VS Code.
Отладка
VS Code содержит встроенный отладчик кода. Вы можете, например, отметить брейкпойнты (точки остановки) и следить за состоянием приложения в реальном времени.
Для отладки бэкенд-кода достаточно встроенных возможностей. Для отладки фронтенд-кода нужно установить плагин для соответствующего браузера:
Подробнее об отладке можно узнать на сайте VS Code.
Ссылки
Курс по настройке окружения для работы в современной экосистеме JavaScript.
JavaScript in Visual Studio Code
Visual Studio Code includes built-in JavaScript IntelliSense, debugging, formatting, code navigation, refactorings, and many other advanced language features.

Most of these features just work out of the box, while some may require basic configuration to get the best experience. This page summarizes the JavaScript features that VS Code ships with. Extensions from the VS Code Marketplace can augment or change most of these built-in features. For a more in-depth guide on how these features work and can be configured, see Working with JavaScript.
IntelliSense
IntelliSense shows you intelligent code completion, hover information, and signature information so that you can write code more quickly and correctly.
Sorry, your browser doesn’t support HTML 5 video.
VS Code provides IntelliSense within your JavaScript projects; for many npm libraries such as React , lodash , and express ; and for other platforms such as node , serverless, or IoT.
See Working with JavaScript for information about VS Code’s JavaScript IntelliSense, how to configure it, and help troubleshooting common IntelliSense problems.
JavaScript projects (jsconfig.json)
A jsconfig.json file defines a JavaScript project in VS Code. While jsconfig.json files are not required, you will want to create one in cases such as:
- If not all JavaScript files in your workspace should be considered part of a single JavaScript project. jsconfig.json files let you exclude some files from showing up in IntelliSense.
- To ensure that a subset of JavaScript files in your workspace is treated as a single project. This is useful if you are working with legacy code that uses implicit globals dependencies instead of imports for dependencies.
- If your workspace contains more than one project context, such as front-end and back-end JavaScript code. For multi-project workspaces, create a jsconfig.json at the root folder of each project.
- You are using the TypeScript compiler to down-level compile JavaScript source code.
To define a basic JavaScript project, add a jsconfig.json at the root of your workspace:
See Working with JavaScript for more advanced jsconfig.json configuration.
Tip: To check if a JavaScript file is part of JavaScript project, just open the file in VS Code and run the JavaScript: Go to Project Configuration command. This command opens the jsconfig.json that references the JavaScript file. A notification is shown if the file is not part of any jsconfig.json project.
Snippets
VS Code includes basic JavaScript snippets that are suggested as you type;
Sorry, your browser doesn’t support HTML 5 video.
There are many extensions that provide additional snippets, including snippets for popular frameworks such as Redux or Angular. You can even define your own snippets.
Tip: To disable snippets suggestions, set editor.snippetSuggestions to "none" in your settings file. The editor.snippetSuggestions setting also lets you change where snippets appear in the suggestions: at the top ( "top" ), at the bottom ( "bottom" ), or inlined ordered alphabetically ( "inline" ). The default is "inline" .
JSDoc support
VS Code understands many standard JSDoc annotations, and uses these annotations to provide rich IntelliSense. You can optionally even use the type information from JSDoc comments to type check your JavaScript.
Sorry, your browser doesn’t support HTML 5 video.
Quickly create JSDoc comments for functions by typing /** before the function declaration, and select the JSDoc comment snippet suggestion:
Sorry, your browser doesn’t support HTML 5 video.
To disable JSDoc comment suggestions, set "javascript.suggest.completeJSDocs": false .
Hover Information
Hover over a JavaScript symbol to quickly see its type information and relevant documentation.

The ⌘K ⌘I (Windows, Linux Ctrl+K Ctrl+I ) keyboard shortcut shows this hover information at the current cursor position.
Signature Help
As you write JavaScript function calls, VS Code shows information about the function signature and highlights the parameter that you are currently completing:

Signature help is shown automatically when you type a ( or , within a function call. Press ⇧⌘Space (Windows, Linux Ctrl+Shift+Space ) to manually trigger signature help.
Auto imports
Automatic imports speed up coding by suggesting available variables throughout your project and its dependencies. When you select one of these suggestions, VS Code automatically adds an import for it to the top of the file.
Just start typing to see suggestions for all available JavaScript symbols in your current project. Auto import suggestions show where they will be imported from:

If you choose one of these auto import suggestions, VS Code adds an import for it.
In this example, VS Code adds an import for Button from material-ui to the top of the file:

To disable auto imports, set "javascript.suggest.autoImports" to false .
Tip: VS Code tries to infer the best import style to use. You can explicitly configure the preferred quote style and path style for imports added to your code with the javascript.preferences.quoteStyle and javascript.preferences.importModuleSpecifier settings.
Formatting
VS Code’s built-in JavaScript formatter provides basic code formatting with reasonable defaults.
The javascript.format.* settings configure the built-in formatter. Or, if the built-in formatter is getting in the way, set "javascript.format.enable" to false to disable it.
For more specialized code formatting styles, try installing one of the JavaScript formatting extensions from the Marketplace.
JSX and auto closing tags
All of VS Code’s JavaScript features also work with JSX:

You can use JSX syntax in both normal *.js files and in *.jsx files.
VS Code also includes JSX-specific features such as autoclosing of JSX tags:
Sorry, your browser doesn’t support HTML 5 video.
Set "javascript.autoClosingTags" to false to disable JSX tag closing.
Code navigation
Code navigation lets you quickly navigate JavaScript projects.
- Go to Definition F12 — Go to the source code of a symbol definition.
- Peek Definition ⌥F12 (Windows Alt+F12 , Linux Ctrl+Shift+F10 ) — Bring up a Peek window that shows the definition of a symbol.
- Go to References ⇧F12 (Windows, Linux Shift+F12 ) — Show all references to a symbol.
- Go to Type Definition — Go to the type that defines a symbol. For an instance of a class, this will reveal the class itself instead of where the instance is defined.
You can navigate via symbol search using the Go to Symbol commands from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ).
- Go to Symbol in File ⇧⌘O (Windows, Linux Ctrl+Shift+O )
- Go to Symbol in Workspace ⌘T (Windows, Linux Ctrl+T )
Rename
Press F2 to rename the symbol under the cursor across your JavaScript project:

Refactoring
VS Code includes some handy refactorings for JavaScript such as Extract function and Extract constant. Just select the source code you’d like to extract and then click on the lightbulb in the gutter or press ( ⌘. (Windows, Linux Ctrl+. ) ) to see available refactorings.

Available refactorings include:
- Extract to method or function.
- Extract to constant.
- Convert between named imports and namespace imports.
- Move to new file.
See Refactorings for more information about refactorings and how you can configure keyboard shortcuts for individual refactorings.
Unused variables and unreachable code
Unused JavaScript code, such the else block of an if statement that is always true or an unreferenced import, is faded out in the editor:

You can quickly remove this unused code by placing the cursor on it and triggering the Quick Fix command ( ⌘. (Windows, Linux Ctrl+. ) ) or clicking on the lightbulb.
To disable fading out of unused code, set "editor.showUnused" to false . You can also disable fading of unused code only in JavaScript by setting:
Organize Imports
The Organize Imports Source Action sorts the imports in a JavaScript file and removes any unused imports:
Sorry, your browser doesn’t support HTML 5 video.
You can run Organize Imports from the Source Action context menu or with the ⇧⌥O (Windows, Linux Shift+Alt+O ) keyboard shortcut.
Organize imports can also be done automatically when you save a JavaScript file by setting:
Code Actions on Save
The editor.codeActionsOnSave setting lets you configure a set of Code Actions that are run when a file is saved. For example, you can enable organize imports on save by setting:
You can also set editor.codeActionsOnSave to an array of Code Actions to execute in order.
Here are some source actions:
- "organizeImports" — Enables organize imports on save.
- "fixAll" — Auto Fix on Save computes all possible fixes in one round (for all providers including ESLint).
- "fixAll.eslint" — Auto Fix only for ESLint.
- "addMissingImports" — Adds all missing imports on save.
See Node.js/JavaScript for more information.
Code suggestions
VS Code automatically suggests some common code simplifications such as converting a chain of .then calls on a promise to use async and await
Sorry, your browser doesn’t support HTML 5 video.
Set "javascript.suggestionActions.enabled" to false to disable suggestions.
Enhance completions with AI
GitHub Copilot is an AI-powered code completion tool that helps you write code faster and smarter. You can use the GitHub Copilot extension in VS Code to generate code, or to learn from the code it generates.

GitHub Copilot provides suggestions for numerous languages and a wide variety of frameworks, and it works especially well for Python, JavaScript, TypeScript, Ruby, Go, C# and C++.
You can learn more about how to get started with Copilot in the Copilot documentation.
Once you have the Copilot extension installed and enabled, you can test it our for your JavaScript projects.
Create a new file — you can use the File: New File command in the Command Palette ( F1 ).
In the JavaScript file, type the following function header:
Copilot will provide a suggestion like the following — use Tab to accept the suggestion:

Inlay hints
Inlay hints add additional inline information to source code to help you understand what the code does.
Parameter name inlay hints show the names of parameters in function calls:

This can help you understand the meaning of each argument at a glance, which is especially helpful for functions that take Boolean flags or have parameters that are easy to mix up.
To enable parameter name hints, set javascript.inlayHints.parameterNames . 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.
Variable type inlay hints show the types of variables that don’t have explicit type annotations.

Property type inlay hints show the type of class properties that don’t have an explicit type annotation.

Parameter type hints show the types of implicitly typed parameters.

Return type inlay hints show the return types of functions that don’t have an explicit type annotation.

References CodeLens
The JavaScript references CodeLens displays an inline count of reference for classes, methods, properties, and exported objects:

To enable the references CodeLens, set "javascript.referencesCodeLens.enabled" to true .
Click on the reference count to quickly browse a list of references:

Update imports on file move
When you move or rename a file that is imported by other files in your JavaScript project, VS Code can automatically update all import paths that reference the moved file:
Sorry, your browser doesn’t support HTML 5 video.
The javascript.updateImportsOnFileMove.enabled setting controls this behavior. Valid settings values are:
- "prompt" — The default. Asks if paths should be updated for each file move.
- "always" — Always automatically update paths.
- "never" — Do not update paths automatically and do not prompt.
Linters
Linters provides warnings for suspicious looking code. While VS Code does not include a built-in JavaScript linter, many JavaScript linter extensions available in the marketplace.
Tip: This list is dynamically queried from the VS Code Marketplace. Read the description and reviews to decide if the extension is right for you.
Type checking
You can leverage some of TypeScript’s advanced type checking and error reporting functionality in regular JavaScript files too. 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 tried to infer types in .js files the same way it does in .ts files. When types cannot be inferred, they can be specified explicitly with JSDoc comments. You can read more about how TypeScript uses JSDoc for JavaScript type checking in Working with JavaScript.
Type checking of JavaScript is optional and opt-in. Existing JavaScript validation tools such as ESLint can be used alongside built-in type checking functionality.
Debugging
VS Code comes with great debugging support for JavaScript. Set breakpoints, inspect objects, navigate the call stack, and execute code in the Debug Console. See the Debugging topic to learn more.
Debug client side
You can debug your client-side code using a browser debugger such as our built-in debugger for Edge and Chrome, or the Debugger for Firefox.
Debug server side
Debug Node.js in VS Code using the built-in debugger. Setup is easy and there is a Node.js debugging tutorial to help you.
Popular extensions
VS Code ships with excellent support for JavaScript but you can additionally install debuggers, snippets, linters, and other JavaScript tools through extensions.
Tip: The extensions shown above are dynamically queried. Click on an extension tile above to read the description and reviews to decide which extension is best for you. See more in the Marketplace.
Next steps
Read on to find out about:
-
— More detailed information about VS Code’s JavaScript support and how to troubleshoot common issues. — Detailed description of the jsconfig.json project file. — Learn more about IntelliSense and how to use it effectively for your language. — Learn how to set up debugging for your application. — A walkthrough to create an Express Node.js application. — VS Code has great support for TypeScript, which brings structure and strong typing to your JavaScript code.
Common questions
Does VS Code support JSX and React Native?
VS Code supports JSX and React Native. You will get IntelliSense for React/JSX and React Native from automatically downloaded type declaration (typings) files from the npmjs type declaration file repository. Additionally, you can install the popular React Native extension from the Marketplace.
To enable ES6 import statements for React Native, you need to set the allowSyntheticDefaultImports compiler option to true . This tells the compiler to create synthetic default members and you get IntelliSense. React Native uses Babel behind the scenes to create the proper run-time code with default members. If you also want to do debugging of React Native code, you can install the React Native Extension.
Does VS Code support the Dart programming language and the Flutter framework?
Yes, there are VS Code extensions for both Dart and Flutter development. You can learn more at the Flutter.dev documentation.
IntelliSense is not working for external libraries
Automatic Type Acquisition works for dependencies downloaded by npm (specified in package.json ), Bower (specified in bower.json ), and for many of the most common libraries listed in your folder structure (for example jquery-3.1.1.min.js ).
ES6 Style imports are not working.
When you want to use ES6 style imports but some type declaration (typings) files do not yet use ES6 style exports, then set the TypeScript compiler option allowSyntheticDefaultImports to true.
Can I debug minified/uglified JavaScript?
Yes, you can. You can see this working using JavaScript source maps in the Node.js Debugging topic.
How do I disable Syntax Validation when using non-ES6 constructs?
Some users want to use syntax constructs like the proposed pipeline ( |> ) operator. However, these are currently not supported by VS Code’s JavaScript language service and are flagged as errors. For users who still want to use these future features, we provide the javascript.validate.enable setting.
With javascript.validate.enable: false , you disable all built-in syntax checking. If you do this, we recommend that you use a linter like ESLint to validate your source code.
Can I use other JavaScript tools like Flow?
Yes, but some of Flow’s language features such as type and error checking may interfere with VS Code’s built-in JavaScript support. To learn how to disable VS Code’s built-in JavaScript support, see Disable JavaScript support.