Перейти к содержимому

Как установить typescript в visual studio code

  • автор:

Компиляция кода TypeScript (ASP.NET Core)

Область применения:yesVisual Studio Visual Studio для Mac noVisual Studio Code no

Используйте пакет NuGet TypeScript, чтобы добавить поддержку TypeScript в проекты ASP.NET Core. Начиная с Visual Studio 2019 рекомендуется использовать пакет NuGet вместо пакета TypeScript. Пакет NuGet TypeScript обеспечивает большую переносимость на разных платформах и средах.

Для проектов ASP.NET Core чаще всего пакеты NuGet используются для компиляции TypeScript с помощью .NET Core CLI. В сценариях .NET пакет NuGet является предпочтительным вариантом, и это единственный способ включить компиляцию TypeScript с помощью команд CLI .NET Core, таких как dotnet build и dotnet publish . Кроме того, для интеграции MSBuild с ASP.NET Core и TypeScript выберите пакет NuGet.

Для проектов на основе системы проектов JavaScript (JSPS) или esproj используйте пакет npm вместо NuGet для добавления поддержки TypeScript.

Добавление поддержки TypeScript с использованием NuGet

Пакет NuGet TypeScript позволяет включить поддержку TypeScript. Когда в проект устанавливается пакет NuGet или TypeScript 3.2 или более новой версии, в редактор загружается соответствующая версия языковой службы TypeScript.

Если среда Visual Studio установлена, файл node.exe, который входит в комплект, в ней будет выбран автоматически. Если у вас не установлена среда Node.js, мы рекомендуем установить версию LTS с веб-сайта Node.js.

Add NuGet package

  1. В Visual Studio откройте проект ASP.NET Core.
  2. Выбор в обозревателе решений Щелкните правой кнопкой узел проекта и выберите Управление пакетами NuGet. На вкладке «Обзор» найдите Microsoft.TypeScript.MSBuild и нажмите кнопку «Установить «, чтобы установить пакет. Visual Studio добавляет пакет NuGet в раздел Зависимости узла в обозревателе решений. Следующая ссылка на пакет добавляется в файл *.csproj.

 all runtime; build; native; contentfiles; analyzers; buildtransitive  
< "compilerOptions": < "noImplicitAny": false, "noEmitOnError": true, "removeComments": false, "sourceMap": true, "target": "es5", "outDir": "wwwroot/js" >, "include": [ "scripts/**/*" ] > 
  • include указывает компилятору, где искать файлы TypeScript (*.ts).
  • Параметр outDir указывает выходную папку для простых файлов JavaScript, транспилированных компилятором TypeScript.
  • Параметр sourceMap указывает, нужно ли компилятору создать файлы sourceMap.

В приведенной выше конфигурации представлен пример базовой конфигурации TypeScript. Сведения о других параметрах см. в разделе о файле tsconfig.json.

Сборка приложения

  1. В проект добавьте файлы TypeScript (.ts) или TypeScript JSX (.tsx), а затем добавьте код TypeScript. В качестве простого примера TypeScript используйте следующий код:
let message: string = 'Hello World'; console.log(message); 

Пример использования gulp с запускателем задач для сборки приложения см. в разделе о ASP.NET Core и TypeScript.

Если возникнут проблемы, из-за которых Visual Studio будет использовать для Node.js или стороннего средства не ту версию, возможно, потребуется задать путь для использования в Visual Studio. Выберите Средства>Параметры. В разделе Проекты и решения выберите Управление веб-пакетами>Внешние веб-инструменты.

Выполнение приложения

Нажмите клавишу F5 или нажмите кнопку «Пуск» в верхней части окна.

Сведения о структуре пакета NuGet

Microsoft.TypeScript.MSBuild.nupkg содержит две основные папки:

  • Папка build. Эта папка содержит два файла. Оба файла представляют собой точки входа: для основного целевого файла TypeScript и файла .props соответственно.
    1. Microsoft.TypeScript.MSBuild.targets. В этом файле указываются переменные, определяющие платформу среды выполнения, например путь к TypeScript.Tasks.dll, перед импортом Microsoft.TypeScript.targets из папки tools.
    2. Microsoft.TypeScript.MSBuild.props. Этот файл используется для импорта Microsoft.TypeScript.Default.props из папки tools и определения свойств, указывающих на то, что сборка инициирована с помощью NuGet.
  • Папка tools. В пакетах версий до 2.3 содержится только папка tsc. На корневом уровне расположены файлы Microsoft.TypeScript.targets и TypeScript.Tasks.dll. В пакетах версии 2.3 и выше на корневом уровне расположены файлы Microsoft.TypeScript.targets и Microsoft.TypeScript.Default.props . Дополнительные сведения об этих файлах см. в разделе о конфигурации MSBuild. Кроме того, в папке содержатся три вложенные папки:
    1. net45. Эта папка содержит библиотеку TypeScript.Tasks.dll и другие библиотеки DLL, от которых она зависит. Если проект создается на платформе Windows, MSBuild использует библиотеки DLL из этой папки.
    2. netstandard1.3. Эта папка содержит другую версию TypeScript.Tasks.dll , которая используется при создании проектов на компьютере с ОС, отличающейся от Windows.
    3. tsc. Эта папка содержит tsc.js , tsserver.js и все файлы зависимостей, которые нужно запускать в качестве скриптов узла.

Примечание. Если Visual Studio установлен, пакет NuGet автоматически выбирает версию node.exe , упаковав ее в Visual Studio. В противном случае на компьютере необходимо установить Node.js.

Удаление файлов, импортированных по умолчанию

В старых проектах ASP.NET Core, где используется формат не в стиле SDK, может потребоваться удалить некоторые элементы файла проекта.

Если вы используете пакет NuGet для поддержки MSBuild в проекте, файл проекта не должен импортировать Microsoft.TypeScript.Default.props или Microsoft.TypeScript.targets . Файлы импортируются пакетом NuGet, поэтому их отдельное включение может привести к непредвиденным последствиям.

  1. Щелкните проект правой кнопкой мыши и выберите пункт Выгрузить проект.
  2. Щелкните проект правой кнопкой мыши и выберите Изменить имя файла проекта>. Откроется файл проекта.
  3. Удалите ссылки на Microsoft.TypeScript.Default.props и Microsoft.TypeScript.targets . Удаляемые импорты имеют примерно следующий вид:

Использование TypeScript в Visual Studio Code

TypeScript – это типизированный расширенный набор JavaScript, который компилируется в простой JavaScript. Давайте разберемся, что именно это означает:

  • типизированный язык позволяет определять переменные, параметры и типы данных.
  • как расширенный набор TypeScript вносит дополнительные функции в стандартный набор JavaScript. Валидный JavaScript является валидным TypeScript, но не наоборот.
  • компиляция в простой JavaScript нужна потому, что TypeScript не запускается браузером. Таким образом, доступные инструменты компилируют TypeScript в понятный браузеру JavaScript.

В этом руководстве мы покажем, как работать с TypeScript в Visual Studio Code, и рассмотрим преимущества их совместного использования.

Требования

  • Базовые навыки работы с JavaScript.
  • Локальная установка Node.js. Найти мануал по установке для вашей системы можно здесь.
  • Установка Visual Studio Code

1: Установка и компиляция TypeScript

Для начала нам нужно выполнить глобальную установку пакета TypeScript на ваш компьютер. Для этого запустите следующую команду в своем терминале:

npm install -g typescript

Затем выполните следующую команду, чтобы создать каталог для вашего проекта:

Перейдите в новый каталог:

Теперь нужно создать новый файл TypeScript. Эти файлы используют расширение .ts.

Теперь вы можете открыть VS Code и создать новый файл, нажав File → New File. После этого сохраните его, нажав File → Save As. В мануале мы назовем этот файл app.ts. В целом же имя файла не имеет значения, важно только его расширение .ts.

Файл должен начинаться со строки export <>;, чтобы VS Code распознал его как модуль.

Создайте функцию, которая будет выводить имя и фамилию из объекта person:

Проблема вышеприведенного кода заключается в том, что в функции welcomePerson нет ограничений, в нее можно передавать любые данные. В TypeScript вы можете создавать интерфейсы, которые определяют, какими свойствами должен обладать объект.

В приведенном ниже фрагменте представлен интерфейс для объекта Person с двумя свойствами: firstName и lastName. Сама же функция welcomePerson была изменена, чтобы принимать только объекты Person.

export <>;
function welcomePerson(person: Person) console.log(`Hey $ $`);
return `Hey $ $`;
>
const james = firstName: «James»,
lastName: «Quick»
>;
welcomePerson(james);
interface Person firstName: string;
lastName: string;
>

Вы поймете преимущество этого хода, если попытаетесь передать в функцию welcomePerson какую-то строку.

Например, давайте заменим james:

Поскольку мы работаем с файлом TypeScript, VS Code немедленно сообщит вам, что функция ожидает объект Person, а не строку.

Argument of type ‘»James»‘ is not assignable to parameter of type ‘Person’.

Теперь, когда у вас есть рабочий файл TypeScript, вы можете скомпилировать его в JavaScript. Для этого вам нужно вызвать функцию и указать, какой файл компилировать. Сделать это можно с помощью встроенного терминала VS Code.

Если вы еще не исправили ошибку, вы увидите такое сообщение:

app.ts:13:15 — error TS2345: Argument of type ‘»James»‘ is not assignable to parameter of type ‘Person’.

Чтобы исправить ошибку, вместо строки передайте функции объект Person, который она ожидает. Затем перезапустите компиляцию. Вы получите рабочий файл JavaScript.

Команда ls выведет список файлов по текущему пути:

Вы увидите исходный файл ts и новый файл js:

Откройте файл app.js в VS Code:

«use strict»;
exports.__esModule = true;
function welcomePerson(person) console.log(«Hey » + person.firstName + » » + person.lastName);
return «Hey » + person.firstName + » » + person.lastName;
>
var james = firstName: «James»,
lastName: «Quick»
>;
welcomePerson(james);

Обратите внимание, что шаблонные литералы, являющиеся функцией ES6, были скомпилированы как простая конкатенация строк в ES5. Скоро мы вернемся к этому вопросу.

Чтобы убедиться, что все работает, вы можете запустить JavaScript непосредственно, используя Node в своем терминале:

В консоли вы увидите имя:

Hey James Quick

2: Создание конфигурационного файла TypeScript

Итак, вы скомпилировали один файл, и это здорово. Но в реальном проекте вам может понадобиться настроить компиляцию всех файлов: к примеру, если файлы нужно будет компилировать в ES6 вместо ES5. Для этого можно создать конфигурационный файл TypeScript.

Чтобы создать этот файл, вы можете запустить следующую команду (подобную npm init):

Вы получите такой вывод:

message TS6071: Successfully created a tsconfig.json file.

Откройте новый файл tsconfig.json, и вы увидите множество различных опций, большинство из них будут закомментированы.

Возможно, вы заметили, что в файле есть опция “target”, которая имеет значение “es5”. Измените ее значение на “es6”.

Внеся это изменение в tsconfig.json, запустите команду tsc в своем терминале:

Примечание: Здесь мы не указываем входной файл, хотя ранее делали это. Официальная документация проекта сообщает: если в командной строке указан входной файл, файлы tsconfig.json будут проигнорированы.

Теперь откройте только что созданный файл app.js:

«use strict»;
Object.defineProperty(exports, «__esModule», < value: true >);
function welcomePerson(person) console.log(`Hey $ $`);
return `Hey $ $`;
>
const james = firstName: «James»,
lastName: «Quick»
>;
welcomePerson(james);

Обратите внимание, что шаблонный литерал здесь сохраняет свой синтаксис, а это доказывает, что TypeScript был успешно скомпилирован в ES6.

Еще одна вещь, которую вы можете изменить – это место, где хранятся файлы JavaScript после создания. За это отвечает параметр “outDir”.

Попробуйте удалить “outDir”, а затем ввести его снова – при этом вы увидите список вариантов для автодополнения. VS Code предоставляет функцию IntelliSense, свойства которой вы можете установить в конфигурационном файле TypeScript.

Для примера можно изменить значение outDir с текущего каталога на каталог dist:

После повторной компиляции (tsc) ваш выходной файл JavaScript будет находиться внутри каталога dist.

Вы можете использовать команды cd и ls в своем терминале, чтобы изучить содержимое каталога dist:

Вы увидите ваш скомпилированный файл JavaScript в новом каталоге:

3: TypeScript и современные фронтэнд фреймворки

За последние пару лет TypeScript стал довольно популярным языком. Вот несколько примеров его использования в современных фреймворках.

Angular CLI

Проекты Angular CLI поставляются с предварительной установкой TypeScript. Все настройки, включая проверку соблюдения стандартов кодирования, встроены в них по умолчанию. Создайте свой простой проект Angular CLI и внимательно изучите его, чтобы увидеть, как выглядит TypeScript в реальном приложении.

Create React App 2

Create React App не предоставляет TypeScript по умолчанию, но в последней версии его можно настроить таким образом. Если вам интересно узнать, как использовать TypeScript с Create React App, смотрите этот мануал.

Vue CLI 3

Vue CLI можно настроить на поддержку TypeScript при создании нового проекта. Больше информации об этом вы можете найти в Vue Docs.

Заключение

В этом мануале мы рассмотрели использование TypeScript в VS Code. TypeScript позволяет генерировать более качественный и надежный JavaScript. Как видите, VS Code предоставляет множество функций, помогающих вам писать TypeScript, генерировать конфигурации и так далее.

TypeScript in Visual Studio Code

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It offers classes, modules, and interfaces to help you build robust components.

Working with TypeScript in Visual Studio Code

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:

npm install -g typescript 

You can test your install by checking the version.

tsc --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.

Hello World

Let’s start with a simple Hello World Node.js example. Create a new folder HelloWorld and launch VS Code.

mkdir HelloWorld cd HelloWorld code . 

From the File Explorer, create a new file called helloworld.ts .

create new file

Now add the following TypeScript code. You’ll notice the TypeScript keyword let and the string type declaration.

let message: string = 'Hello World'; console.log(message); 

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.

compiled hello world

If you have Node.js installed, you can run node helloworld.js .

run hello world

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 .

var message = 'Hello World'; console.log(message); 

IntelliSense

IntelliSense shows you intelligent code completion, hover information, and signature help so that you can write code more quickly and correctly.

TypeScript small completions for String type

VS Code provides IntelliSense for individual TypeScript files as well as TypeScript tsconfig.json projects.

Hover information

Hover over a TypeScript symbol to quickly see its type information and relevant documentation:

Hover for a lodash function

You can also show the hover information 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 for the lodash capitalize function

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.

Snippets

In addition to smart code completions, VS Code also includes basic TypeScript snippets that are suggested as you type.

TypeScript

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» .

Errors and warnings

The TypeScript language service will analyze your program for coding problems and report errors and warnings:

  • In the Status bar, there is a summary of all errors and warnings counts.
  • You can click on the summary or press ⇧⌘M (Windows, Linux Ctrl+Shift+M ) to display the PROBLEMS panel with a list of all current errors.
  • If you open a file that has errors or warnings, they will be rendered inline with the text and in the overview ruler.

Error in the editor and Problems panel

To loop through errors or warnings in the current file, you can press F8 or ⇧F8 (Windows, Linux Shift+F8 ) which will show an inline zone detailing the problem and possible Code Actions (if available):

Error inline in the editor

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 )

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.

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 light bulb in the gutter or press ( ⌘. (Windows, Linux Ctrl+. ) ) to see available refactorings.

TypeScript refactoring

See Refactoring TypeScript for more information about refactorings and how you can configure keyboard shortcuts for individual refactorings.

Rename

One of the simplest refactorings is to rename a method or variable. Press F2 to rename the symbol under the cursor across your TypeScript project:

Renaming a method

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 Debugging TypeScript and the overall 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 fix many of 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:

  • TypeScript tutorial — Create a simple Hello World TypeScript in VS Code.
  • Editing TypeScript — Specific editing features for TypeScript.
  • Refactoring TypeScript — Useful refactorings from the TypeScript language service.
  • Compiling TypeScript — Compile TypeScript to a JavaScript target version.
  • Debugging TypeScript — 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 2022?

No, the TypeScript language service that ships with Visual Studio 2019 and 2022 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.

TypeScript tutorial in Visual Studio Code

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:

npm install -g typescript 

You can test your install by checking the version.

tsc --version 

Hello World

Let’s start with a simple Hello World Node.js example. Create a new folder HelloWorld and launch VS Code.

mkdir HelloWorld cd HelloWorld code . 

From the File Explorer, create a new file called helloworld.ts .

create new file

Now add the following TypeScript code. You’ll notice the TypeScript keyword let and the string type declaration.

let message: string = 'Hello World'; console.log(message); 

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.

compiled hello world

If you have Node.js installed, you can run node helloworld.js .

run hello world

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 .

var message = 'Hello World'; console.log(message); 

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

IntelliSense

When you select a method, you then get parameter help and can always get hover information.

parameter help

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 that set the options to compile to ES5 and use CommonJS modules.

 "compilerOptions":  "target": "ES5", "module": "CommonJS"  > > 

When editing tsconfig.json , IntelliSense ( ⌃Space (Windows, Linux Ctrl+Space ) ) will help you along the way.

tsconfig.json IntelliSense

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.

 "compilerOptions":  "target": "ES5", "module": "CommonJS", "outDir": "out"  > > 

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.

incorrect type error

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 light bulb.

unreachable code detected

Clicking on the light bulb 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 .

 "compilerOptions":  "target": "ES5", "module": "CommonJS", "outDir": "out", "sourceMap": true  > > 

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.

debug console output

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 and Debug view ( ⇧⌘D (Windows, Linux Ctrl+Shift+D ) ).

debug breakpoint

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:

  • Compiling TypeScript — Use VS Code’s powerful task system for compiling TypeScript.
  • Editing TypeScript — Specific editing features for TypeScript.
  • Refactoring TypeScript — Useful refactorings from the TypeScript language service.
  • Debugging 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.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

https://kapelnicza.vyvod-iz-zapoya-v-stacionare-samara12.ru/