Name already in use
vscode-docs / docs / languages / javascript.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
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 shows you intelligent code completion, hover information, and signature information so that you can write code more quickly and correctly.
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.
VS Code includes basic JavaScript snippets that are suggested as you type;
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» .
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.
Quickly create JSDoc comments for functions by typing /** before the function declaration, and select the JSDoc comment snippet suggestion:
To disable JSDoc comment suggestions, set «javascript.suggest.completeJSDocs»: false .
Hover over a JavaScript symbol to quickly see its type information and relevant documentation.

The kb(editor.action.showHover) keyboard shortcut shows this hover information at the current cursor position.
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 kb(editor.action.triggerParameterHints) to manually trigger signature help.
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.
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:
Set «javascript.autoClosingTags» to false to disable JSX tag closing.
Code navigation lets you quickly navigate JavaScript projects.
- Go to Definition kb(editor.action.revealDefinition) — Go to the source code of a symbol definition.
- Peek Definition kb(editor.action.peekDefinition) — Bring up a Peek window that shows the definition of a symbol.
- Go to References kb(editor.action.goToReferences) — 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 ( kb(workbench.action.showCommands) ).
- Go to Symbol in File kb(workbench.action.gotoSymbol)
- Go to Symbol in Workspace kb(workbench.action.showAllSymbols)
Press kb(editor.action.rename) to rename the symbol under the cursor across your JavaScript project:

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 ( kb(editor.action.quickFix) ) 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 ( kb(editor.action.quickFix) ) 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:
The Organize Imports Source Action sorts the imports in a JavaScript file and removes any unused imports:
You can run Organize Imports from the Source Action context menu or with the kb(editor.action.organizeImports) 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.
VS Code automatically suggests some common code simplifications such as converting a chain of .then calls on a promise to use async and await
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 ( kbstyle(F1) ).
In the JavaScript file, type the following function header:
Copilot will provide a suggestion like the following — use kbstyle(Tab) to accept the suggestion:

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.

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:
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 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.
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.
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.
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.
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.
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.
Базовая настройка редактора VS Code для JavaScript разработки
HTML, CSS
В этой статье я привожу базовые настройки для удобной работы в редакторе Visual Studio Code для frontend разработки. Будет приведен список плагинов (расширений) и рекомендуемые настройки редактора.
Список плагинов для VS Code
Внешний вид
Ayu — тема для редактора
Удобная, яркая, контрастная тема для редактора и подсветки кода. Хорошо подходит как для работы ночью, так и в яркий солнечный день.
Тема оформление редактора Ayu
Мой выбор темы: Ayu Mirage Border.
Material Icon Theme
Яркие, симпатичные иконки для файлов в панели навигации.
Верстка, расширения общего назначения
Auto Complete Tag — автозакрытие и авто-переименование тегов
Bracket Pair Colorizer — подсветка скобок <. >[. ]
Subtle Match Brackets — подсветка парных скобок
Live Server — запуск локального сервера
Prettier — Code formatter — автоформатирование кода
Russian Language Pack for Visual Studio — русификация редактора
Сниппеты для JS кода
js snippets — сниппеты для JavaScript
Simple React Snippets — сниппеты для React JS
Настройки редактора
Файл → Автосохранение файлов
Настройки emmet
Параметры → emmet → Trigger Expansion On Tab → Ставим чекбокс
Параметры текста
Размер шрифта, высота строки, шрифтовое семейство.
Editor: Line Height → 26
Editor: Font Size → 14
Editor Font Family → Consolas, ‘Courier New’, monospace
How to run JavaScript in Visual Studio Code
This article conveys the execution of JavaScript in VSCode. The steps to run JavaScript inside Visual Studio are as follows:
1. The first step is the installation of Node.js on your MacBook/Windows in order to call scripts through Node.js. You can easily download Node.js by visiting https://nodejs.org/en/
2. In the second step you have to create a new folder then open this folder in Visual Studio Code. Subsequently, write JavaScript code and save it with an extension of “.js”.
3. Open up the operating system’s terminal inside Visual Studio Code by clicking on View on the topmost bar.

Example
To run a script named index.js in Visual Studio Code then you should first make sure that node.js is installed. Open the terminal within Visual Studio Code. You can now easily run JavaScript in the terminal of VSCode by using node.js. The syntax of the node command used to run JavaScript code is shown in the VSCode terminal.
In this example, we wrote the script to check if the number is even or odd. Subsequently, we execute the command in the terminal as shown below to get the output. In this case, we assigned 6 to the num variable and it gives the following output.
// this script used to check if the number is even or odd
const result = ( num % 2 != 0 ) ? "odd" : "even" ;
// display the result
console. log ( ` Number is $ { result } .` ) ;
Output

On the other hand, we assigned 43 to the num variable and it gives the following output.
// this script used to check if the number is even or odd
const result = ( num % 2 != 0 ) ? "odd" : "even" ;
// display the result
console. log ( ` Number is $ { result } .` ) ;
Output

An alternative way to run JavaScript in VSCode using Code Runner Extension
This is the simplest method to run JavaScript. There are no configurations required in this method. You need to install Node.js either way on your machines as the code runner extension also needs Node.js. Following steps must be kept in mind to run JavaScript in VSCode using a code runner extension.
1. First of all, you need to install Code Runner Extension in order to run JavaScript code. This extension will consume a couple of minutes to install and it is really easy to install it. You can easily download the code runner extension by visiting https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner

Then click on the Open URL:vscode button. The following window is shown as mentioned below.

2. After installation of the code runner extension, open JavaScript Code in VSCode. Press CTRL+ALT+N shortcut or you may press F1 then write Run Code to run the code. Subsequently, you will see the following output in the “OUTPUT” tab.
// this script used to check if the number is even or odd
const result = ( num % 2 != 0 ) ? "odd" : "even" ;
// display the result
console. log ( ` Number is $ { result } .` ) ;
Output:

Conclusion
Visual Studio gives quality, flexibility and also gives outstanding debugging experience to web applications using JavaScript. So, in order to run/execute JavaScript in Visual Studio Code we need NodeJS which acts as an interpreter. In this article, we demonstrate how to run JavaScript in Visual Studio Code and also explain an alternative way to run JavaScript in VSCode using Code Runner Extension along with detailed examples.
JavaScript
Visual Studio Code uses the TypeScript language service to make authoring JavaScript easy. In addition to syntactical features like format, format on type and outlining, you also get language service features such as Peek, Go to Definition, Find all References, and Rename Symbol.
JavaScript Projects (jsconfig.json)
VS Code’s JavaScript support can operate in two different modes:
File Scope — no jsconfig.json: In this mode, JavaScript files opened in Visual Studio Code are treated as independent units. As long as a file a.js doesn’t reference a file b.ts explicitly (either using /// reference directives or CommonJS modules), there is no common project context between the two files.
Explicit Project — with jsconfig.json: A JavaScript project is defined via a jsconfig.json file. The presence of such a file in a directory indicates that the directory is the root of a JavaScript project. The file itself can optionally list the files belonging to the project, the files to be excluded from the project, as well as compiler options (see below).
The JavaScript experience is much better when you have a jsconfig.json file in your workspace that defines the project context. For this reason, we provide a hint to create a jsconfig.json file when you open a JavaScript file in a fresh workspace. The jsconfig.json file corresponds to a TypeScript project tsconfig.json file with the attribute allowJs implicitly set to true . If no files attribute is present, then this defaults to including all files in the containing directory and subdirectories. When a files attribute is specified, only those files are included.
Make sure that you place the jsconfig.json at the root of your JavaScript project and not just at the root of your workspace. Below is a jsconfig.json file which defines the JavaScript target to be ES6 and the exclude attribute excludes the node_modules folder.
Here is an example with an explicit files attribute.
The files attribute cannot be used in conjunction with the exclude attribute. If both are specified, the files attribute takes precedence.
In more complex projects, you may have more than one jsconfig.json file defined inside a workspace, as illustrated in below for a project with a client and server folder, that are a separate project context:

Excludes
Whenever possible, you should exclude folders with JavaScript files that are not part of the source code for your project.
Note: If you do not have a jsconfig.json in your workspace, VS Code will by default exclude the node_modules folder and the folder defined by the out attribute.
Below is a table mapping common project components to their installation folders which are recommended to exclude:
| Component | folder to exclude |
|---|---|
| node | exclude the node_modules folder |
| webpack , webpack-dev-server | exclude the content folder, e.g., dist . |
| bower | exclude the bower_components folder |
| ember | exclude the tmp and temp folders |
| jspm | exclude the jspm_packages folder |
When your JavaScript project is growing too large, it is often because of library folders like node_modules . If VS Code detects that your project is growing too large, it will prompt you to edit the exclude list.
Tip: Sometimes changes to configuration, such as adding or editing a jsconfig.json file are not picked up correctly. Running the Reload JavaScript Project command should reload the project and pick up the changes.
jsconfig Options
Below are jsconfig options to configure the JavaScript language support.
| Option | Description |
|---|---|
| noLib | Do not include the default library file (lib.d.ts) |
| target | Specifies which default library (lib.d.ts) to use. The values are «ES3», «ES5», «ES6». |
| experimentalDecorators | Enables experimental support for proposed ES decorators. |
| allowSyntheticDefaultImports | Allow default imports from modules with no default export. This does not affect code emit, just typechecking. |
IntelliSense
The JavaScript Support uses different strategies to provide IntelliSense.
IntelliSense based on type inference
JavaScript uses the same inference as TypeScript to determine the type of a value.
The following patterns are also recognized:
- «ES3-style» classes, specified using a constructor function and assignments to the prototype property.
- CommonJS-style module patterns, specified as property assignments on the exports object, or assignments to the module.exports property.
The AMD (Asynchronous Module Definition) module pattern is currently not supported.
IntelliSense offers both inferred proposals and the global identifiers of the project. The inferred symbols are presented first, followed by the global identifiers (with the document icon), as you can see in the image below.

JSDoc annotations
Where type inference does not provide the desired type information, (or just for documentation purposes), type information may be provided explicitly via JSDoc annotations.
This document describes the JSDoc annotations currently supported.
TypeScript definition file
You can also get IntelliSense for libraries through the use of type definition .d.ts files. DefinitelyTyped is a repository of typings files for all major JavaScript libraries and environments. The typings are easily managed using Typings, the TypeScript Definition manager.
For example typings install dt
node —global installs all the typings for the built-in Node.js modules. If your project has a jsconfig.json file, then make sure that typings is contained in the project context defined by the location of the jsconfig.json file. If you have no jsconfig.json , then you need to manually add a /// reference to the .d.ts from each JavaScript file.
Tip: When you want to use ES6 style imports but the typings do not yet use ES6 style exports, then set the TypeScript compiler option allowSyntheticDefaultImports to true.
Mixed TypeScript and JavaScript projects
It is now possible to have mixed TypeScript and JavaScript projects. Existing JavaScript code using the CommonJS module format, may be imported and consumed by TypeScript code using the ECMAScript 2015 module syntax. Conversely, TypeScript code written to provide a well-defined API contract for a service, may be referenced by JavaScript code that is written to call that service, thus providing rich IntelliSense at design time.
To enable JavaScript inside a TypeScript project, you can set the allowJs property to true in the TypeScript project’s tsconfig.json file.
Compiling JavaScript down-level
One of the key features TypeScript provides 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, e.g. tsc -p jsconfig.json to down-level compile.
The following compiler options in jsconfig.json apply when tsc is used for down level compiling of ES6 JavaScript to an older version:
| Option | Description |
|---|---|
| module | Specify module code generation. The values are «commonjs», «system», «umd», «amd», «es6», «es2015» |
| diagnostics | Show diagnostic information. |
| emitBOM | Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. |
| inlineSourceMap | Emit a single file with source maps instead of having a separate file. |
| inlineSources | Emit the source alongside the sourcemaps within a single file; requires —inlineSourceMap to be set. |
| jsx | Specify JSX code generation: «preserve» or «react». |
| reactNamespace | Specifies the object invoked for createElement and __spread when targeting ‘react’ JSX emit. |
| mapRoot | Specifies the location as an uri in a string where debugger should locate map files instead of generated locations. |
| noEmit | Do not emit output. |
| noEmitHelpers | Do not generate custom helper functions like __extends in compiled output. |
| noEmitOnError | Do not emit outputs if any type checking errors were reported. |
| noResolve | Do not resolve triple-slash references or module import targets to the input files. |
| outFile | Concatenate and emit output to single file. |
| outDir | Redirect output structure to the directory. |
| removeComments | Do not emit comments to output. |
| rootDir | Specifies the root directory of input files. Use to control the output directory structure with —outDir. |
| sourceMap | Generates corresponding ‘.map’ file. |
| sourceRoot | Specifies the location where debugger should locate JavaScript files instead of source locations. |
| stripInternal | `do not emit declarations for code that has an ‘@internal’ annotation. |
| watch | Watch input files. |
| emitDecoratorMetadata | Emit design-type metadata for decorated declarations in source. |
| noImplicitUseStrict | Do not emit «use strict» directives in module output. |
JavaScript Formatting
VS Code provides several formatting settings for JavaScript. They can all be found in the javascript.format settings name space.
Snippets for JavaScript
VS Code has several built-in snippets that will come up as you type or you can press kb(editor.action.triggerSuggest) (Trigger Suggest) and you will see a context specific list of suggestions.

Selecting the snippet with kbstyle(Tab) results in:

Tip: You can add in your own User Defined Snippets for JavaScript. See User Defined Snippets to find out how.
Run Babel inside VS Code
The Babel transpiler turns ES6 files into readable ES5 JavaScript with Source Maps. You can easily integrate Babel into your workflow by adding this code to your tasks.json file (located under the workspace’s .vscode folder). The isBuildCommand switch makes this task the Task: Run Build Task gesture. isWatching tells VS Code not to wait for this task to finish. To learn more, go to Tasks.
Once you have added this, you can start Babel with the kb(workbench.action.tasks.build) (Run Build Task) command and it will compile all files from the src directory into the lib directory.
JSX and React Native
VS Code supports JSX and React Native. To get IntelliSense for React/JSX, install the typings for react-global by running typings install dt
react-global —global from the terminal. To get IntelliSense for React Native, run typings install dt
React Native examples often use the experimental Object Rest/Spread operator. This is not yet supported by VS Code. If you want to use it, it is recommended that you disable the built-in syntax checking (see below).
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 then you can install the React Native Extension.
Disable Syntax Validation when using non ES6 constructs
Some users want to use syntax constructs like the proposed Object Rest/Spread Properties. However, these are currently not supported by VS Code’s JavaScript support 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 code. Since the JavaScript support doesn’t understand ES7 constructs, features like IntelliSense might not be fully accurate.
JavaScript Linters (ESLint, JSHint)
VS Code provides support for ESLint and JSHint via extensions. If enabled, the JavaScript code is validated as you type and reported problems can be navigated to and fixed inside VS Code.
To enable one of the linters, do the following:
- Install the corresponding linter globally or inside the workspace folder that contains the JavaScript code to be validated. For example, using npm install -g eslint or npm install -g jshint , respectively.
- Install the ESLint or JSHint extension. The linter is enabled after installation. You can disable a linter via the corresponding settings «eslint.enable»: true or «jshint.enable»: true , respectively.
- Use a .eslintrc.json or .jshintrc file in the root of your workspace to configure the linter. You can use eslint —init to create an initial version of the .eslintrc.json file.
Tip: You get IntelliSense and hovering inside the .eslintrc.json and the .jshintrc files.
It is recommended that you enable the linter rules that warn about undefined and unused variables.