Запустить typescript в visual studio code
Поддержку TypeScript можно добавить в проекты с помощью TypeScript SDK или с помощью npm. TypeScript SDK доступен по умолчанию в Visual Studio Installer.
Для проектов, которые разработаны в Visual Studio 2019, рекомендуется использовать пакеты npm TypeScript. Они обеспечивают лучшую переносимость между разными средами и платформами.
Добавление поддержки TypeScript с использованием npm
Пакет npm TypeScript позволяет включить поддержку TypeScript. Когда в проект устанавливается пакет npm или TypeScript 2.1 или более новой версии, в редактор загружается соответствующая версия языковой службы TypeScript.
Следуя инструкциям, установите рабочую нагрузку разработки Node.js и среду выполнения Node.js.
Для простой интеграции с Visual Studio создайте проект с помощью одного из шаблонов Node.js для TypeScript, например шаблона пустого веб-приложения Node.js. Либо используйте шаблон Node.js для JavaScript, предоставляемый в Visual Studio, и следуйте инструкциям в этом разделе. Или используйте проект Открытая папка
Установите пакет npm для TypeScript, если он еще не включен в ваш проект.
В Обозревателе решений (область справа) откройте package.json в корневом каталоге проекта. Перечисленные пакеты соответствуют пакетам в узле npm в Обозревателе решений. Дополнительные сведения см. в разделе Управление пакетами npm.
Установить пакет npm TypeScript для проекта Node.js можно с помощью командной строки или IDE. Чтобы установить пакет с помощью IDE, щелкните правой кнопкой мыши узел npm в Обозревателе решений, выберите Установить новый пакет npm, найдите TypeScript и установите пакет.
Выберите параметр npm в окне Вывод, чтобы видеть ход установки пакета. Установленный пакет появится в узле npm в Обозревателе решений.
Если пакет не включен в проект, добавьте файл с tsconfig.json в корневой каталог проекта. Для этого щелкните правой кнопкой мыши узел проекта и выберите Добавить > Новый элемент. Выберите Файл конфигурации TypeScript JSON, а затем нажмите кнопку Добавить.
Visual Studio добавит файл tsconfig.json в корневую папку проекта. Этот файл можно использовать для настройки параметров компилятора TypeScript.
Откройте файл tsconfig.json и обновите его, задав необходимые параметры компилятора.
Ниже приведен пример простого файла tsconfig.json.
- include указывает компилятору, где искать файлы TypeScript (*.ts).
- Параметр outDir указывает выходную папку для обычных файлов JavaScript, которые преобразуются компилятором TypeScript.
- Параметр sourceMap указывает, нужно ли компилятору создать файлы sourceMap.
В приведенной выше конфигурации представлен пример базовой конфигурации TypeScript. Сведения о других параметрах см. в разделе о файле tsconfig.json.
Построение приложения
В проект добавьте файлы TypeScript ( .ts) или TypeScript JSX ( .tsx), а затем добавьте код TypeScript. Ниже приведен простой пример TypeScript:
В package.json включите поддержку команд сборки и очистки Visual Studio, используя приведенные ниже скрипты.
Для сборки с помощью стороннего средства, например webpack, можно добавить в файл package.json скрипт сборки для командной строки:
Пример использования webpack с React и файла конфигурации webpack см. в статье Учебник. Создание приложения Node.js и React в Visual Studio.
Пример использования Vue.js с TypeScript см. в статье Создание приложения Vue.js.
Если необходимо настроить такие параметры, как начальная страница, путь к среде выполнения Node.js, порт приложения или аргументы среды выполнения, щелкните правой кнопкой мыши узел проекта в Обозревателе решений и выберите Свойства.
При настройке сторонних средств в проектах Node.js не используются пути, заданные в разделе Средства > Параметры > Проекты и решения > Управление веб-пакетами > Внешние веб-инструменты. Эти параметры используются для проектов других типов.
Выберите Сборка > Собрать решение.
Сборка приложения выполняется автоматически при его запуске. Однако в процессе сборки могут возникнуть следующие проблемы:
Если вы создали сопоставители с исходным кодом, откройте папку, указанную в параметре outDir, где вы найдете созданные файлы *.js, а также созданные файлы *js.map.
Файлы сопоставителей с исходным кодом требуются для отладки.
Выполнение приложения
Инструкции по запуску приложения после его компиляции см. в разделе Создание приложения Node.js и Express.
Автоматизация задач сборки
Для автоматизации задач сторонних средств, таких как npm и webpack, вы можете использовать обозреватель запускателя задач в Visual Studio.
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It offers classes, modules, and interfaces to help you build robust components.
Installing the TypeScript compiler
Visual Studio Code includes TypeScript language support but does not include the TypeScript compiler, tsc . You will need to install the TypeScript compiler either globally or in your workspace to transpile TypeScript source code to JavaScript ( tsc HelloWorld.ts ).
The easiest way to install TypeScript is through npm, the Node.js Package Manager. If you have npm installed, you can install TypeScript globally ( -g ) on your computer by:
You can test your install by checking the version.
Another option is to install the TypeScript compiler locally in your project ( npm install --save-dev typescript ) and has the benefit of avoiding possible interactions with other TypeScript projects you may have.
Syntax highlighting and semantic highlighting
In addition to syntax highlighting, TypeScript and JavaScript also provide semantic highlighting.
Syntax highlighting colors the text based on lexical rules. Semantic highlighting enriches the syntax coloring based on resolved symbol information from the language service.
Whether semantic highlighting is visible depends on the current color theme. Each theme can configure whether to display semantic highlighting and how it styles the semantic tokens.
If semantic highlighting is enabled and the color theme has a corresponding styling rule defined, different colors and styles can be seen.
Semantic highlighting can change colors based on:
- The resolved type of a symbol: namespace, variable, property, variable, class, interface, typeParameter.
- Whether the variable/property is read-only (const) or modifiable.
- Whether the variable/property type is callable (a function type) or not.
IntelliSense
IntelliSense shows you intelligent code completion, hover info, 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 for individual TypeScript files as well as TypeScript tsconfig.json projects.
Snippets
VS Code includes basic TypeScript snippets that are suggested as you type;
Sorry, your browser doesn't support HTML 5 video.
You can install extensions to get additional snippets or define your own snippets for TypeScript. See User Defined Snippets for more information.
Tip: You can disable snippets by setting editor.snippetSuggestions to "none" in your settings file. If you'd like to see snippets, you can specify the order relative to suggestions; at the top ( "top" ), at the bottom ( "bottom" ), or inlined ordered alphabetically ( "inline" ). The default is "inline" .
JSDoc support
VS Code's TypeScript IntelliSense understands many standard JSDoc annotations, and uses them to show typing information and documentation in suggestions, hover info, and signature help.
Keep in mind that when using JSDoc for TypeScript code, you should not include type annotations. The TypeScript compiler only uses TypeScript type annotations and ignores those from JSDoc.
Sorry, your browser doesn't support HTML 5 video.
To disable JSDoc comment suggestions in TypeScript, set "typescript.suggest.completeJSDocs": false .
Hover information
Hover over a TypeScript symbol to quickly see its type information and relevant documentation:
You can also show the hover info at the current cursor position with the ⌘K ⌘I (Windows, Linux Ctrl+K Ctrl+I ) keyboard shortcut.
Signature help
As you write a TypeScript function call, 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. Use ⇧⌘Space (Windows, Linux Ctrl+Shift+Space ) to manually trigger signature help.
Auto imports
Automatic imports speed up coding by helping you find available symbols and automatically adding imports for them.
Just start typing to see suggestions for all available TypeScript symbols in your current project.
If you choose one of the suggestions from another file or module, VS Code will automatically add an import for it. In this example, VS Code adds an import for Hercules to the top of the file:
You can disable auto imports by setting "typescript.suggest.autoImports": false .
Formatting
VS Code includes a TypeScript formatter that provides basic code formatting with reasonable defaults.
Use the typescript.format.* settings to configure the built-in formatter, such as making braces appear on their own line. Or, if the built-in formatter is getting in the way, set "typescript.format.enable" to false to disable it.
For more specialized code formatting styles, try installing one of the formatting extensions from the VS Code marketplace.
JSX and auto closing tags
VS Code's TypeScript features also work with JSX. To use JSX in your TypeScript, use the *.tsx file extension instead of the normal *.ts :
VS Code also includes JSX-specific features such as autoclosing of JSX tags in TypeScript:
Sorry, your browser doesn't support HTML 5 video.
Set "typescript.autoClosingTags" to false to disable JSX tag closing.
Code navigation
Code navigation lets you quickly navigate TypeScript 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.
- Go to Implementation ⌘F12 (Windows, Linux Ctrl+F12 ) - Go to the implementations of an interface or abstract method.
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 TypeScript project:
Refactoring
VS Code includes some handy refactorings for TypeScript 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.
See Refactorings for more information about refactorings and how you can configure keyboard shortcuts for individual refactorings.
Available TypeScript refactorings include:
Extract to method or function - Extract the selected statements or expressions to either a new method or a new function in the file.
After selecting the Extract to method or Extract to function refactoring, enter the name of the extracted method/function.
Extract to constant - Extract the selected expression to a new constant in the file.
Extract type to interface or type alias - Extract the selected complex type to either an interface or a type alias.
Move to new file - Move one or more classes, functions, constants, or interfaces in the top-level scope of the file to a new file. The new file's name is inferred from the selected symbol's name.
Convert between named imports and namespace imports - Convert between named imports ( import < Name >from './foo' ) and namespace imports ( import * as foo from './foo' ).
Convert between default export and named export - Convert from using a export default and having a named export ( export const Foo = . ).
Generate get and set accessors - Encapsulate a selected class property by generating a getter and setter for it.
Convert parameters to destructured object - Rewrite a function that takes a long list of arguments to take a single arguments object.
Quick Fixes
Quick Fixes are suggested edits that address simple coding errors. Example Quick Fixes include:
- Adding a missing this to a member access.
- Fixing a misspelled property name.
- Removing unreachable code or unused imports
- Declaring
When you move your cursor on to a TypeScript error, VS Code shows a lightbulb that indicates that Quick Fixes are available. Click the lightbulb or press ⌘. (Windows, Linux Ctrl+. ) to show a list of available Quick Fixes and refactorings.
Unused variables and unreachable code
Unused TypeScript code, such as 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 TypeScript by setting:
Organize Imports
The Organize Imports source code action sorts the imports in a TypeScript file and removes 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 TypeScript 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 TypeScript 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 "typescript.suggestionActions.enabled" to false to disable suggestions.
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 typescript.inlayHints.parameterNames.enabled . 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 TypeScript references CodeLens displays an inline count of reference for classes, interfaces, methods, properties, and exported objects:
You can enable this by setting "typescript.referencesCodeLens.enabled": true in the User Settings file.
Click on the reference count to quickly browse a list of references:
Implementations CodeLens
The TypeScript implementations CodeLens displays the number of implementors of an interface:
You can enable this by setting "typescript.implementationsCodeLens.enabled": true .
As with the references CodeLens, you can click on the implementation count to quickly browse a list of all implementations.
Update imports on file move
When you move or rename a file that is imported by other files in your TypeScript project, VS Code can automatically update all import paths that reference the moved file.
- "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.
Debugging
VS Code comes with great debugging support for TypeScript, including support for sourcemaps. 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 the built-in Edge and Chrome debugger, 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.
Linters
Linters provides warnings for suspicious looking code. While VS Code does not include a built-in TypeScript linter, TypeScript linter extensions available in the marketplace.
ESLint is a popular linter, which also supports TypeScript. The ESLint extension integrates ESLint into VS Code so you can see linting errors right in the editor and even quickly many of fix them with Quick Fixes. The ESLint plugin guide details how to configure ESLint for your TypeScript projects.
TypeScript extensions
VS Code provides many features for TypeScript out of the box. In addition to what comes built-in, you can install an extension for greater functionality.
Tip: 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
To learn more, see:
-
- Create a simple Hello World TypeScript in VS Code. - Compile TypeScript to a JavaScript target version. - Learn about debugging TypeScript both server and client-side with VS Code.
Common questions
Can I use the version of TypeScript that ships with VS 2015?
No, the TypeScript language service that ships with Visual Studio 2015 and 2017 isn't compatible with VS Code. You will need to install a separate version of TypeScript from npm.
How can I use the latest TypeScript beta with VS Code?
The simplest way to try out the latest TypeScript features in VS Code is to install the JavaScript and TypeScript Nightly extension.
Visual Studio Code supports TypeScript debugging through its built-in Node.js debugger and Edge and Chrome debugger.
JavaScript source map support
TypeScript debugging supports JavaScript source maps. To generate source maps for your TypeScript files, compile with the --sourcemap option or set the sourceMap property in the tsconfig.json file to true .
In-lined source maps (a source map where the content is stored as a data URL instead of a separate file) are also supported, although in-lined source is not yet supported.
For a simple example of source maps in action, see the TypeScript tutorial, which shows debugging a simple "Hello World" Node.js application using the following tsconfig.json and VS Code default Node.js debugging configuration.
For more advanced debugging scenarios, you can create your own debug configuration launch.json file. To see the default configuration, go to the Run view ( ⇧⌘D (Windows, Linux Ctrl+Shift+D ) ) and press the gear icon or Create a launch.json link to Configure or Fix 'launch.json'.
This will create a launch.json file in a .vscode folder with default values detected in your project.
VS Code has determined the program to launch, helloworld.ts , included the build as a preLaunchTask , and told the debugger where to find the generated JavaScript files.
There is full IntelliSense with suggestions and information for launch.json to help you learn about other debug configuration options. You can also add new debug configurations to launch.json with the Add Configuration button in the lower right.
Also see Node.js Debugging for examples and further explanations.
Mapping the output location
If generated (transpiled) JavaScript files do not live next to their source, you can help the VS Code debugger locate them by setting the outFiles attribute in the launch configuration. Whenever you set a breakpoint in the original source, VS Code tries to find the generated source by searching the files specified by glob patterns in outFiles .
Client-side debugging
TypeScript is great for writing client-side code as well as Node.js applications and you can debug client-side source code with the built-in Edge and Chrome debugger.
We'll create a tiny web application to show client-side debugging in action.
Create a new folder HelloWeb and add three files: helloweb.ts , helloweb.html , and tsconfig.json with the following content"
Run tsc to build the app and then test by opening helloweb.html in your browser (you can right-click helloweb.html in the File Explorer and select Copy Path to paste into your browser).
In the Run view, press the gear icon to create a launch.json file selecting Edge: launch as the debugger, or Chrome if you prefer.
Update the launch.json to specify the local file URL to helloweb.html :
The Run view configuration dropdown will now show the new configuration Launch Edge against localhost. If you run that configuration, your browser will launch with your web page. Open helloweb.ts in the editor and click the left gutter to add a breakpoint (it will be displayed as a red circle). Press F5 to start the debug session, which launches the browser and hits your breakpoint in helloweb.ts .
Common questions
Cannot launch program because corresponding JavaScript cannot be found
You've likely not set "sourceMap": true in your tsconfig.json or outFiles in your launch.json and the VS Code Node.js debugger can't map your TypeScript source code to the running JavaScript. Turn on source maps and rebuild your project.
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It offers classes, modules, and interfaces to help you build robust components.
Install the TypeScript compiler
Visual Studio Code includes TypeScript language support but does not include the TypeScript compiler, tsc . You will need to install the TypeScript compiler either globally or in your workspace to transpile TypeScript source code to JavaScript ( tsc HelloWorld.ts ).
The easiest way to install TypeScript is through npm, the Node.js Package Manager. If you have npm installed, you can install TypeScript globally ( -g ) on your computer by:
You can test your install by checking the version.
Hello World
Let's start with a simple Hello World Node.js example. Create a new folder HelloWorld and launch VS Code.
From the File Explorer, create a new file called helloworld.ts .
Now add the following TypeScript code. You'll notice the TypeScript keyword let and the string type declaration.
To compile your TypeScript code, you can open the Integrated Terminal ( ⌃` (Windows, Linux Ctrl+` ) ) and type tsc helloworld.ts . This will compile and create a new helloworld.js JavaScript file.
If you have Node.js installed, you can run node helloworld.js .
If you open helloworld.js , you'll see that it doesn't look very different from helloworld.ts . The type information has been removed and let is now var .
IntelliSense
In VS Code, you can see that you get language features such as syntax highlighting and bracket matching. When you were typing in the editor, you may have noticed IntelliSense, the smart code completions and suggestions provided by VS Code and the TypeScript language server. Below you can see the methods of console
When you select a method, you then get parameter help and can always get hover information.
tsconfig.json
So far in this tutorial, you have been relying on the TypeScript compiler's default behavior to compile your TypeScript source code. You can modify the TypeScript compiler options by adding a tsconfig.json file that defines the TypeScript project settings such as the compiler options and the files that should be included.
Important: To use tsconfig.json for the rest of this tutorial, invoke tsc without input files. The TypeScript compiler knows to look at your tsconfig.json for project settings and compiler options.
Add a simple tsconfig.json which set the options to compile to ES5 and use CommonJS modules.
When editing tsconfig.json , IntelliSense ( ⌃Space (Windows, Linux Ctrl+Space ) ) will help you along the way.
By default, TypeScript includes all the .ts files in the current folder and subfolders if the files attribute isn't included, so we don't need to list helloworld.ts explicitly.
Change the build output
Having the generated JavaScript file in the same folder as the TypeScript source will quickly get cluttered on larger projects, so you can specify the output directory for the compiler with the outDir attribute.
Delete helloworld.js and run the command tsc with no options. You will see that helloworld.js is now placed in the out directory.
See Compiling TypeScript to learn about other features of the TypeScript language service and how to use tasks to run your builds directly from VS Code.
Error checking
TypeScript helps you avoid common programming mistakes through strong type checking. For example, if you assign a number to message , the TypeScript compiler will complain with 'error TS2322: Type '2' is not assignable to type 'string'. You can see type checking errors in VS Code both in the editor (red squiggles with hover information) and the Problems panel ( ⇧⌘M (Windows, Linux Ctrl+Shift+M ) ). The [ts] prefix lets you know this error is coming from the TypeScript language service.
Quick Fixes
The TypeScript language service has a powerful set of diagnostics to find common coding issues. For example, it can analyze your source code and detect unreachable code which is displayed as dimmed in the editor. If you hover over the line of source code, you'll see a hover explaining and if you place your cursor on the line, you'll get a Quick Fix lightbulb.
Clicking on the lightbulb or pressing ⌘. (Windows, Linux Ctrl+. ) brings up the Quick Fix menu where you can select the Remove unreachable code fix.
Debugging
VS Code has built-in support for TypeScript debugging. To support debugging TypeScript in combination with the executing JavaScript code, VS Code relies on source maps for the debugger to map between the original TypeScript source code and the running JavaScript. You can create source maps during the build by setting "sourceMap": true in your tsconfig.json .
Rebuild by running tsc and you should now have a helloworld.js.map in the out directory next to helloworld.js .
With helloworld.ts open in the editor, press F5 . If you have other debugger extensions installed, you need to select Node.js from the dropdown.
The debugger will start a session, run your code, and display the "Hello World" message in the Debug console panel.
In helloworld.ts , set a breakpoint by clicking on the left gutter of the editor. You will see a red circle if the breakpoint is set. Press F5 again. Execution will stop when the breakpoint is hit and you'll be able to see debugging information such as variable values and the call stack in the Run view ( ⇧⌘D (Windows, Linux Ctrl+Shift+D ) ).
See Debugging TypeScript to learn more about VS Code's built-in debugging support for TypeScript and how you can configure the debugger for your project scenarios.
Next steps
This tutorial was a quick introduction to using VS Code for TypeScript development. Read on to learn more about using VS Code's compiling and debugging support for TypeScript:
-
- Use VS Code's powerful task system for compiling TypeScript. - Configure the debugger for your TypeScript project.
Common questions
Cannot launch program because corresponding JavaScript cannot be found
You've likely not set "sourceMap": true in your tsconfig.json and the VS Code Node.js debugger can't map your TypeScript source code to the running JavaScript. Turn on source maps and rebuild your project.
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It offers classes, modules, and interfaces to help you build robust components.
Install the TypeScript compiler
Visual Studio Code includes TypeScript language support but does not include the TypeScript compiler, tsc . You will need to install the TypeScript compiler either globally or in your workspace to transpile TypeScript source code to JavaScript ( tsc HelloWorld.ts ).
The easiest way to install TypeScript is through npm, the Node.js Package Manager. If you have npm installed, you can install TypeScript globally ( -g ) on your computer by:
You can test your install by checking the version or help.
Another option is to install the TypeScript compiler locally in your project ( npm install --save-dev typescript ) and has the benefit of avoiding possible interactions with other TypeScript projects you may have.
Compiler versus language service
It is important to keep in mind that VS Code's TypeScript language service is separate from your installed TypeScript compiler. You can see the VS Code's TypeScript version in the Status Bar when you open a TypeScript file.
Later in the article, we'll discuss how you can change the version of TypeScript language service that VS Code uses.
tsconfig.json
Typically the first step in any new TypeScript project is to add a tsconfig.json file. A tsconfig.json file defines the TypeScript project settings, such as the compiler options and the files that should be included. To do this, open up the folder where you want to store your source and add a new file named tsconfig.json . Once in this file, IntelliSense ( ⌃Space (Windows, Linux Ctrl+Space ) ) will help you along the way.
A simple tsconfig.json looks like this for ES5, CommonJS modules and source maps:
Now when you create a .ts file as part of the project we will offer up rich editing experiences and syntax validation.
Transpile TypeScript into JavaScript
VS Code integrates with tsc through our integrated task runner. We can use this to transpile .ts files into .js files. Another benefit of using VS Code tasks is that you get integrated error and warning detection displayed in the Problems panel. Let's walk through transpiling a simple TypeScript Hello World program.
Step 1: Create a simple TS file
Open VS Code on an empty folder and create a helloworld.ts file, place the following code in that file.
To test that you have the TypeScript compiler tsc installed correctly and a working Hello World program, open a terminal and type tsc helloworld.ts . You can use the Integrated Terminal ( ⌃` (Windows, Linux Ctrl+` ) ) directly in VS Code.
You should now see the transpiled helloworld.js JavaScript file, which you can run if you have Node.js installed, by typing node helloworld.js .
Step 2: Run the TypeScript build
Execute Run Build Task ( ⇧⌘B (Windows, Linux Ctrl+Shift+B ) ) from the global Terminal menu. If you created a tsconfig.json file in the earlier section, this should present the following picker:
Select the tsc: build entry. This will produce a HelloWorld.js and HelloWorld.js.map file in the workspace.
If you selected tsc: watch, the TypeScript compiler watches for changes to your TypeScript files and runs the transpiler on each change.
Under the covers, we run the TypeScript compiler as a task. The command we use is: tsc -p .
Step 3: Make the TypeScript Build the default
You can also define the TypeScript build task as the default build task so that it is executed directly when triggering Run Build Task ( ⇧⌘B (Windows, Linux Ctrl+Shift+B ) ). To do so, select Configure Default Build Task from the global Terminal menu. This shows you a picker with the available build tasks. Select TypeScript tsc: build, which generates the following tasks.json file in a .vscode folder:
Notice that the task has a group JSON object that sets the task kind to build and makes it the default. Now when you select the Run Build Task command or press ( ⇧⌘B (Windows, Linux Ctrl+Shift+B ) ), you are not prompted to select a task and your compilation starts.
Tip: You can also run the program using VS Code's Run/Debug feature. Details about running and debugging Node.js applications in VS Code can be found in the Node.js tutorial
Step 4: Reviewing build issues
The VS Code task system can also detect build issues through a problem matcher. A problem matcher parses build output based on the specific build tool and provides integrated issue display and navigation. VS Code ships with many problem matchers and $tsc seen above in tasks.json is the problem matcher for TypeScript compiler output.
As an example, if there was a simple error (extra 'g' in console.log ) in our TypeScript file, we may get the following output from tsc :
This would show up in the terminal panel ( ⌃` (Windows, Linux Ctrl+` ) ) and selecting the Tasks - build tsconfig.json in the terminal view dropdown.
You can see the error and warning counts in the Status Bar. Click on the error and warnings icon to get a list of the problems and navigate to them.
You can also use the keyboard to open the list ⇧⌘M (Windows, Linux Ctrl+Shift+M ) .
Tip: Tasks offer rich support for many actions. Check the Tasks topic for more information on how to configure them.
JavaScript source map support
TypeScript debugging supports JavaScript source maps. To generate source maps for your TypeScript files, compile with the --sourcemap option or set the sourceMap property in the tsconfig.json file to true .
In-lined source maps (a source map where the content is stored as a data URL instead of a separate file) are also supported, although in-lined source is not yet supported.
Output location for generated files
Having the generated JavaScript file in the same folder at the TypeScript source will quickly get cluttered on larger projects. You can specify the output directory for the compiler with the outDir attribute.
Hiding derived JavaScript files
When you are working with TypeScript, you often don't want to see generated JavaScript files in the File Explorer or in Search results. VS Code offers filtering capabilities with a files.exclude workspace setting and you can easily create an expression to hide those derived files:
This pattern will match on any JavaScript file ( **/*.js ) but only if a sibling TypeScript file with the same name is present. The File Explorer will no longer show derived resources for JavaScript if they are compiled to the same location.
Add the files.exclude setting with a filter in the workspace settings.json file, located in the .vscode folder at the root of the workspace. You can open the workspace settings.json via the Preferences: Open Workspace Settings (JSON) command from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ).
To exclude JavaScript files generated from both .ts and .tsx source files, use this expression:
This is a bit of a trick. The search glob pattern is used as a key. The settings above use two different glob patterns to provide two unique keys but the search will still match the same files.
Using newer TypeScript versions
VS Code ships with a recent stable version of the TypeScript language service and uses this by default to provide IntelliSense in your workspace. The workspace version of TypeScript is independent of the version of TypeScript you use to compile your *.ts files. You can just use VS Code's built-in TypeScript version for IntelliSense without worry for most common cases, but sometimes you may need to change the version of TypeScript VS Code uses for IntelliSense.
Reasons for doing this include:
- Trying out the latest TypeScript features by switching to the TypeScript nightly build ( typescript@next ).
- Making sure you are using the same version of TypeScript for IntelliSense that you use to compile your code.
The active TypeScript version and its install location are displayed in the Status Bar when viewing a TypeScript file:
You have a few options if you want to change the default version of TypeScript in your workspace:
Using the workspace version of TypeScript
If your workspace has a specific TypeScript version, you can switch between the workspace version of TypeScript and the version that VS Code uses by default by opening a TypeScript or JavaScript file and clicking on the TypeScript version number in the Status Bar. A message box will appear asking you which version of TypeScript VS Code should use:
Use this to switch between the version of TypeScript that comes with VS Code and the version of TypeScript in your workspace. You can also trigger the TypeScript version selector with the TypeScript: Select TypeScript Version command.
VS Code will automatically detect workspace versions of TypeScript that are installed under node_modules in the root of your workspace. You can also explicitly tell VS Code which version of TypeScript to use by configuring the typescript.tsdk in your user or workspace settings. The typescript.tsdk setting should point to a directory containing the TypeScript tsserver.js file. You can find the TypeScript installation location using npm list -g typescript . The tsserver.js file is usually in the lib folder.
Tip: To get a specific TypeScript version, specify @version during npm install. For example, for TypeScript 3.6.0, you would use npm install --save-dev typescript@3.6.0 . To preview the next version of TypeScript, run npm install --save-dev typescript@next .
Note that while typescript.tsdk points to the lib directory inside of typescript in these examples, the typescript directory must be a full TypeScript install that contains the TypeScript package.json file.
You can also tell VS Code to use a specific version of TypeScript in a particular workspace by adding a typescript.tsdk workspace setting pointing to the directory of the tsserver.js file:
The typescript.tsdk workspace setting only tells VS Code that a workspace version of TypeScript exists. To actually start using the workspace version for IntelliSense, you must run the TypeScript: Select TypeScript Version command and select the workspace version.
Using TypeScript nightly builds
The simplest way to try out the latest TypeScript features in VS Code is to install the JavaScript and TypeScript Nightly extension.
This extension automatically replaces VS Code's built-in TypeScript version with the latest TypeScript nightly build. Just make sure you switch back to using VS Code's TypeScript version if you've configured your TypeScript version with the TypeScript: Select TypeScript Version command.
Mixed TypeScript and JavaScript projects
It is possible to have mixed TypeScript and JavaScript projects. To enable JavaScript inside a TypeScript project, you can set the allowJs property to true in the tsconfig.json .
Tip: The tsc compiler does not detect the presence of a jsconfig.json file automatically. Use the –p argument to make tsc use your jsconfig.json file, e.g. tsc -p jsconfig.json .
Working with large projects
If you are working in a codebase with hundreds or thousands of TypeScript files, here are some steps you can take to improve both the editing experience in VS Code as well as compile times on the command line.
Make sure your tsconfig only includes files you care about
Use include or files in your project's tsconfig.json to make sure the project only includes the files that should be part of the project.
More information on configuring your project's tsconfig.json .
Break up your project using project references
Instead of structuring your source code as a single large project, you can improve performance by breaking it up into smaller projects using project references. This allows TypeScript to load just a subset of your codebase at a time, instead of loading the entire thing.
See the TypeScript documentation for details on how to use project references and best practices for working with them.
Next steps
Read on to find out about:
-
- Configure the debugger for your TypeScript project.
Common questions
How do I resolve a TypeScript "Cannot compile external module" error?
If you get that error, resolve it by creating a tsconfig.json file in the root folder of your project. The tsconfig.json file lets you control how Visual Studio Code compiles your TypeScript code. For more information, see the tsconfig.json overview.
Why do I get different errors and warnings with VS Code than when I compile my TypeScript project?
VS Code ships with a recent stable version of the TypeScript language service and it may not match the version of TypeScript installed globally on your computer or locally in your workspace. For that reason, you may see differences between your compiler output and errors detected by the active TypeScript language service. See Using newer TypeScript versions for details on installing a matching TypeScript version.
Can I use the version of TypeScript that ships with VS 2015?
No, the TypeScript language service that ships with Visual Studio 2015 and 2017 isn't compatible with VS Code. You will need to install a separate version of TypeScript from npm.
Why are some errors reported as warnings?
By default, VS Code TypeScript displays code style issues as warnings instead of errors. This applies to:
- Variable is declared but never used
- Property is declared but its value is never read
- Unreachable code detected
- Unused label
- Fall through case in switch
- Not all code paths return a value
Treating these as warnings is consistent with other tools, such as TSLint. These will still be displayed as errors when you run tsc from the command line.
You can disable this behavior by setting "typescript.reportStyleChecksAsWarnings": false in your User settings.
Читайте также: