Running and debugging TypeScript
With WebStorm, you can run and debug client-side TypeScript code and TypeScript code running in Node.js.
Debugging of TypeScript client-side code is only supported in Google Chrome and in other Chromium-based browsers.
For more information about running and debugging TypeScript with Angular, refer to Running and debugging Angular applications.
Before running or debugging an application, you need to compile your TypeScript code into JavaScript. You can do that using the built-in TypeScript compiler and other tools, including ts-node for running TypeScript with Node.js, used separately or as part of build process.
During compilation, there can also be generated source maps that set correspondence between your TypeScript code and the JavaScript code that is actually executed. As a result, you can set breakpoints in your TypeScript code, launch the application with the run/debug configuration of the type JavaScript Debug (for client-side code) or Node.js , and then step through your original TypeScript code, thanks to generated sourcemaps.
Run a client-side TypeScript application
You can write a client-side application in TypeScript, compile the code as described in Compiling TypeScript into JavaScript, and then run and debug your application exactly in the same way as client-side applications written in JavaScript. The only difference is that you can set breakpoints right in the TypeScript code.
- Compile the TypeScript code into JavaScript.
- In the editor, open the HTML file with a reference to the generated JavaScript file. This HTML file does not necessarily have to be the one that implements the starting page of the application.
- Do one of the following:
- Choose View | Open in Browser from the main menu or press Alt F2 . Then select the desired browser from the list.
- Hover over the code to show the browser icons bar: . Click the icon that indicates the desired browser.
Debug a client-side TypeScript application
If your application is running on the built-in WebStorm server , refer to Running a client-side TypeScript application above, you can also debug it in the same way as JavaScript running on the built-in server.
Debug a TypeScript application running on an external web server
Most often, you may want to debug a client-side application running on an external development web server, for example, powered by Node.js.
- Configure the built-in debugger as described in Configuring JavaScript debugger.
- To enable source maps generation, open your tsconfig.json and set the sourceMap property to true , as described in Create a tsconfig.json file.
- Configure and set breakpoints in the TypeScript code.
- Run the application in the development mode . Often you need to run npm start for that. Most often, at this stage TypeScript is compiled into JavaScript and source maps are generated. For more information, refer to Compiling TypeScript into JavaScript. When the development server is ready, copy the URL address at which the application is running in the browser — you will need to specify this URL address in the run/debug configuration.
- Go to Run | Edit Configurations . Alternatively, select Edit Configurations from the list on the toolbar. In the Edit Configurations dialog that opens, click the Add button () on the toolbar and select JavaScript Debug from the list. In the Run/Debug Configuration: JavaScript Debug dialog that opens, specify the URL address at which the application is running. This URL can be copied from the address bar of your browser as described in Step 3 above.

- Select the newly created configuration from the Select run/debug configuration list on the toolbar and click the Debug button () next to the list. The URL address specified in the run configuration opens in the browser and the Debug tool window appears. You may need to refresh the page in the browser to get the controls in the Debug tool window available.
- In the Debug tool window, proceed as usual: step through the program, stop and resume the program execution, examine it when suspended, view actual HTML DOM, run JavaScript code snippets in the Console, and so on.
Run and debug a server-side TypeScript application with Node.js
With WebStorm, you can launch server-side TypeScript code on Node.js via the Node.js run configuration. Before running or debugging, your TypeScript code has to be compiled into JavaScript, as described in Compiling TypeScript into JavaScript.
For debugging, also make sure that compilation produces source maps that set correspondence between your TypeScript code and the JavaScript code that is actually executed. For more information, refer to Create a tsconfig.json file.
Before you start
- Make sure you have Node.js on your computer.
- Make sure the Node.js plugin is enabled in the settings. Press Control+Alt+S to open the IDE settings and then select Plugins . Click the Installed tab. In the search field, type Node.js . For more information about plugins, refer to Managing plugins.
- To enable source maps generation, open your tsconfig.json and set the sourceMap property to true , as described in Create a tsconfig.json file.
Create a Node.js run/debug configuration

- Go to Run | Edit Configurations . Alternatively, select Edit Configurations from the list on the toolbar.
In the Edit Configurations dialog that opens, click the Add button () on the toolbar and select Node.js from the list. - In the Run/Debug Configuration: Node.js dialog that opens, specify the Node.js interpreter to use. In the JavaScript File field, specify the compiled file generated from the main file of the application that starts it.
Run server-side TypeScript with Node.js
- Compile your TypeScript code into JavaScript. For more information, refer to Compiling TypeScript into JavaScript.
- Create a Node.js run/debug configuration as described above.
- Select the newly created Node.js configuration from the Select run/debug configuration list on the toolbar and click the Run button () next to the list.
Debug server-side TypeScript with Node.js
- Compile your TypeScript code into JavaScript. For more information, refer to Compiling TypeScript into JavaScript.
- Set the breakpoints in the TypeScript code where necessary.
- Create a Node.js run/debug configuration as described above.
- Select the newly created Node.js configuration from the Select run/debug configuration list on the toolbar and click the Debug button () next to the list. The Debug tool window opens.
- Perform the steps that will trigger the execution of the code with the breakpoints.
- Switch to WebStorm, where the controls of the Debug tool window are now enabled.
Use ts-node
If you need to run or debug single TypeScript files with Node.js, you can use ts-node instead of compiling your code as described in Compiling TypeScript into JavaScript.
Install ts-node
- In the embedded Terminal ( Alt+F12 ) , type: npm install —save-dev ts-node
Create a custom Node.js run/debug configuration for ts-node
- Go to Run | Edit Configurations . Alternatively, select Edit Configurations from the list on the toolbar.
In the Edit Configurations dialog that opens, click the Add button () on the toolbar and select Node.js from the list. The Run/Debug Configuration: Node.js dialog opens. - In the Node Parameters field, add —require ts-node/register .
- Specify the Node.js interpreter to use. If you choose the Project alias, WebStorm will automatically use the project default interpreter from the Node interpreter field on the Node.js page . In most cases, WebStorm detects the project default interpreter and fills in the field itself. You can also choose another configured local or remote interpreter or click and configure a new one. For more information, refer to Configuring remote Node.js interpreters, Configuring a local Node.js interpreter, and Using Node.js on Windows Subsystem for Linux.
- In the JavaScript File field, specify the TypeScript file to run or debug. Depending on your workflow, you can do that explicitly or using a macro.
- If you are going to always launch the same TypeScript file, click and select this file in the dialog that opens. By default, the run/debug configuration gets the name of the selected file.
- If you need to launch different files, type $FilePathRelativeToProjectRoot$ . With this macro, WebStorm will always launch the file in the active editor tab.
- If necessary, specify any additional parameters for ts-node (for example, —project tsconfig.json ) in the Application parameters field.
- Save the configuration.

Run a TypeScript file with ts-node
Depending on the way you specified your TypeScript file in the run/debug configuration, do one of the following:
- If you typed the filename explicitly, select the required configuration from the list on the toolbar and click next to the list or press Shift+F10 .
- If you specified a macro, open the TypeScript file to run in the editor, select the newly created configuration from the list on the toolbar, and click or press Shift+F10 .
WebStorm shows the output in the Run tool window.
Debug a TypeScript file with ts-node
- In the TypeScript file to debug, set the breakpoints as necessary.
- Depending on the way you specified your TypeScript file in the run/debug configuration, do one of the following:
- If you typed the filename explicitly, select the required configuration from the list on the toolbar and click next to the list or press Shift+F9 .
- If you specified a macro, open the TypeScript file to debug in the editor, select the newly created configuration from the list on the toolbar, and click next to the list or press Shift+F9 .
TypeScript. Зачем он нужен и почему так популярен
JavaScript-код должен работать предсказуемо в любой ситуации. Мы можем добавить в него огромное количество проверок, но тогда он станет громоздким, и его будет сложно сопровождать. Или можно добавить комментарии и подсказки, но это не защитит нас от неверного использования кода. В такой ситуации на помощь приходит TypeScript. Давайте разбираться, чем он полезен для JavaScript-разработчиков.
Что такое TypeScript?
TypeScript — строго типизированный язык программирования, основанный на JavaScript. Он состоит из трёх частей:
- синтаксис языка программирования,
- компилятор,
- сервис для редактора.
Синтаксис TypeScript позволяет разработчику элегантно выразить решение задачи в виде текста в файле .ts или .tsx . Он является эволюцией синтаксиса JavaScript, поэтому любая программа JS синтаксически корректна на TypeScript.
Компилятор tsc помогает обнаружить множество дефектов до загрузки на продакшн. Он преобразует исходный текст TypeScript в JavaScript и анализирует программу, стараясь найти проблемные места. TypeScript может создать. js-файлы для любой версии JavaScript, начиная с ES3. Разработчик может диктовать TypeScript, какие правила анализа активировать, а какие — отключить.
Такие дефекты не всегда являются ошибками. Порой они долгое время не приводят к нарушению технического задания, но при появлении новых требований со стороны заказчика становятся причиной неоправданного удорожания работы.
Например, в JavaScript есть оператор try catch . В блок catch приходит значение с информацией об ошибке. Это значение может быть чем угодно, например, строкой, числом или объектом. В JavaScript разработчик на свой страх и риск использует «опыт и догадки». Один из вариантов поведения разработчиков — верить, что информация об ошибке будет типа Error .
В TypeScript можно заставить компилятор проверить использование значения в catch , а можно это правило отключить:
catch(err)
Будет ошибкой, если err — число 42.
Если поставить флаг компилятора useUnknownInCatchVariables , то компилятор не разрешит код из примера. Он заставит разработчика подумать, как выйти из положения, и тем самым снизит риск аварийного завершения программы.
Сервис для редактора выполняет такой же анализ, как и tsc-компилятор, но он это делает по мере того, как вы пишете программу. Есть множество редакторов с поддержкой TypeScript — например, с ним точно работают VS Code, Atom, WebStorm и Sublime Text. Если в списке нет редактора, которым вы пользуетесь, то для знакомства можете использовать песочницу TS Playground.
Онлайн-редактор TS Playground создан для изучения TypeScript. Он позволяет исследовать все важные аспекты этого языка программирования, подключить модули из npm, изучить назначения флагов компилятора, рассмотреть полученный JavaScript и текст определения модуля (.d. ts). При этом песочница обладает ограниченными возможностями для запуска полученного JavaScript.
Сервисы компилятора TypeScript сопровождают вас и указывают на ошибки, когда вы пишете код.
Узнайте больше о теории типов, научитесь на практике использовать аннотацию типов и обобщённое программирование на профессиональном курсе по TypeScript.
Что говорит сообщество?
Опросы Stack Overflow в 2020 и 2021 годах показывают, что предпочтения профессиональных разработчиков и работодателей меняются. В рейтинге популярности языков программирования Stack Overflow за последние два года JavaScript сохраняет лидирующую позицию, но TypeScript стремительно его догоняет:
Популярность языка на SO
Статистика Github за четвёртый квартал 2021 года показывает аналогичную тенденцию:
Доля пулреквестов
Изменение к прошлому году
Разработчики часто обращают внимание на то, что новый сотрудник, и джун, и мидл, быстрее вливается в коллектив TypeScript-проекта, чем в коллектив JavaScript-проекта. Неудивительно, что для соискателя знание TypeScript становится преимуществом.
Исследования использования различных языков программирования на основе статистики пользователей Github показывают, что на TypeScript чаще всего переходят с других языков. Похоже, разработчики всё чаще забрасывают какой-нибудь CoffeeScript и начинают программировать на TypeScript.
Роль TypeScript в вашей работе
Создатели TypeScript ставят перед собой задачу: помочь разработчикам создавать и развивать продукты для любой системы, умеющей исполнять JavaScript, и добавить разработчикам уверенность в том, что программа будет выполняться предсказуемым образом.
Программы похожи на теоремы: они состоят из утверждений, и мы можем задуматься, нет ли в этих утверждениях противоречий. Нам это важно, потому что при наличии противоречий программа может ошибиться во время выполнения.
Убедиться в отсутствии противоречий в программе на TypeScript проще, чем сделать то же самое для программы на JavaScript. Всё дело в аннотации типов.
В TypeScript каждая переменная, функция и класс явно или опосредованно имеет специальные указания о том, значения какого типа в ней содержатся. Эти указания доступны не только для разработчика, но и для редактора и компилятора. Именно благодаря этим аннотациям сервисы TypeScript помогают находить логические противоречия в исходном коде.
Вот как можно озвучить работу сервисов TypeScript в таком отрывке:
const title = "TypeScript"; console.log(title.toUpperCase());
- Известно, что в JavaScript к строковому значению можно применить метод toUpperCase .
- В любой среде выполнения JavaScript есть console.log.
- Программист объявил неизменяемую переменную.
- Значение объявленной переменной — строка.
- Поскольку (1), (3) и (4), к переменной всегда можно применить метод toUpperCase .
- Вывод: поскольку (2) и (5), программа будет всегда исполняться.
Эта цепочка рассуждений появляется благодаря знаниям о том, что можно и нельзя делать со значениями переменных.
Часто TypeScript сам догадывается о возможных действиях. Например, он хорошо ориентируется в примитивных значениях, унаследованных от JavaScript. В отношении кастомных типов разработчик может объяснить TypeScript свои намерения.
В этом и заключается ваше взаимодействие с TypeScript. Вы объясняете ему, какие значения хотите использовать, а он подсказывает, какие операции можно применять в разных ситуациях. Вот ещё один пример «рассуждений» TypeScript:
let title: string; console.log(title.toUpperCase());
Разработчик объявил намерение использовать в переменной строковые значения. Переменная осталась неинициализированной. При отсутствии значения нельзя применять метод toUpperCase
После этих рассуждений TypeScript сообщает об ошибке Variable ‘title’ is used before being assigned до начала выполнения программы. Ещё до того, как вы закончите печатать вторую точку с запятой! К этому времени вы не успеете забыть, зачем объявили переменную title , и потратите меньше времени на исправление ситуации.

Часто способность TypeScript находить подобные дефекты и требовать от разработчика их устранения вызывает раздражение у начинающих программистов. Действительно, кому приятно признавать свои ошибки? Но с опытом приходит понимание, что подсказки компилятора важны для создания качественных продуктов.
TypeScript — это гораздо больше, чем сервис проверки типов. Он выполняет и другие задачи:
- Определяет синтаксис, чтобы разработчик мог выразить намерение использовать значения определённого типа let title: string; .
- Контролирует правомерность использования значения в контексте программы title.toUpperCase() .
- Сообщает разработчику об ошибочном использовании операций в отношении переменных прямо в редакторе, до запуска программы.
- Даёт возможность разработки в методологии ООП. Ключевые слова private, protected, public, abstract, extends, implements .
- Позволяет создавать JavaScript любой версии от JS3 и выше.
- Даёт возможность использовать модули любого формата.
- Открывает возможность обобщённого программирования. Дженерики позволяют создавать компоненты с реализацией алгоритмов в общем виде.
- Позволяет работать в методике аспектного программирования через пока ещё нестандартные декораторы.
- Позволяет создавать и дополнять аннотациями типов существующие библиотеки JavaScript. Да и стандартные тоже.
- Компилирует JSX не только для React, вы можете предоставить свою реализацию createElement .
- Интегрируется с Babel, Browserify, Grunt, Gulp, Jspm, MSBuild, NuGet, Rollup, Svelte Compiler, Vite, Webpack.
- Является Open Source-проектом под «накидкой» Microsoft.
И это лишь часть полезных возможностей и особенностей TypeScript.
Несколько примеров помощи со стороны TypeScript
В процессе компиляции TypeScript создаёт красивый JavaScript. Вы можете убедиться в этом сами в песочнице TypeScript Playground. Для наглядности, вот что происходит с определением класса в старых версиях JavaScript:
TypeScript
class Example<>
Флаг компилятора -target=ES3
use strict"; var Example = /** @class */ (function () < function Example() < >return Example; >());"
Согласитесь, удобнее написать одну строку на TypeScript и запустить компилятор, чем выписывать IIFE — непосредственно вызванное функциональное выражение.
Всегда рискованно создавать вручную необходимый инфраструктурный код, ведь ошибиться легко, а найти ошибку — сложно. TypeScript форматирует модули любого стандарта для вас. Вот как он отформатирует UMD-модуль. Сравните:
TypeScript
import < useState, useEffect >from "react"; interface ComponentProps < delay: number; >export const Component = (props: ComponentProps) => < const < delay >= props; const [elapsed, setElapsed] = useState(false); useEffect(() => < let cleaned = false; setTimeout(() => < if (cleaned) < return; >setElapsed(true); >, delay) return () => < cleaned = true; >; >, [delay]) return >
JavaScript-результат с флагом module=UMD
function (factory) < if (typeof module === "object" && typeof module.exports === "object") < var v = factory(require, exports); if (v !== undefined) module.exports = v; >else if (typeof define === "function" && define.amd) < define(["require", "exports", "react"], factory); >>)(function (require, exports) < "use strict"; Object.defineProperty(exports, "__esModule", < value: true >); exports.Component = void 0; const react_1 = require("react"); const Component = (props) => < const < delay >= props; const [elapsed, setElapsed] = (0, react_1.useState)(false); (0, react_1.useEffect)(() => < let cleaned = false; setTimeout(() => < if (cleaned) < return; >setElapsed(true); >, delay); return () => < cleaned = true; >; >, [delay]); return React.createElement("h1", null, elapsed ? 'loading' : 'completed'); >; exports.Component = Component; >);
Где вы столкнётесь с TypeScript?
При использовании Angular: если разработчик захочет использовать инструменты Angular, ему придётся окунуться в TypeScript. Вы, конечно, можете продолжать «ангулярить» на JavaScript, но это будет непросто.
Другие популярные фреймворки и библиотеки не настолько категоричны, но все они поддерживают разработку на TypeScript. С одной стороны, это неудивительно, ведь TypeScript превращается в обычный JavaScript после компиляции. С другой стороны, участники проекта потратили ценные ресурсы на создание файлов с описанием типов. Следовательно, они рассматривают TypeScript в качестве стратегии развития.
Многие библиотеки, в частности, Redux, уже несколько последних версий создаются сначала на TypeScript и собираются в npm-пакеты после компиляции в JavaScript.
А ещё TypeScript позволяет методично и предсказуемо портировать кодовую базу из JavaScript. Мы предвидим, что разработчики, сопровождающие легаси-проекты этим воспользуются, и тогда вам точно пригодится знание TypeScript.
Что дальше?
TypeScript имеет родственную связь с JavaScript, но обладает собственным синтаксисом и самостоятельной системой компиляции. Умелое использование этих особенностей в проекте позволяет значительно снизить риски появления программных дефектов. С помощью TypeScript разработчик получает более предсказуемый результат в процессе разработки и рефакторинга. Но TypeScript требует знаний.
Для успешного использования TypeScript разработчики должны уметь создавать и описывать типы значений, понимать, как эти типы между собой взаимодействуют — значит, разработчикам придётся учиться. По нашему мнению, лучше приложить немного усилий для изучения TypeScript сейчас, чем позже прикладывать массу сил, чтобы избежать встречи с ним.
Должны ли вы применять TypeScript в каждом своем проекте и какой язык программирования лучше? На эти вопросы, скорее всего, нет ответа, потому что они неверно поставлены. Следует задать вопрос о том, какое преимущество тот или иной язык программирования принесёт вашему проекту. В этом случае в процессе развития проекта, при появлении новых запросов со стороны заказчика, TypeScript будет каждый раз более и более выгодным в сравнении с JavaScript.
Узнать больше
- Почему разработчики выбирают Vue
- Зачем фронтендерам React, если есть JavaScript
- Для чего использовать дженерики в TypeScript
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.
How I «Run» a TypeScript file in WebStorm?
In my WebStorm IDE, all .js (and .jsx ) files in my project have an associated «Run» command, but this feature is absent from .ts (or .tsx ) files. I believe I have correctly configured my project for TypeScript, as I am able to at least run tsc from the command line (with somewhat unexpected results), but am surprised that I can’t simply do this from within the IDE. Does WebStorm support single file TypeScript compilation and running? Does enabling this require some specific non-default configuration of the IDE?
asked Aug 13, 2019 at 16:40
45.8k 58 58 gold badges 208 208 silver badges 428 428 bronze badges
tsc doesn’t run TypeScript, it compiles it. is that what you are trying to do? Where would you run it? On node? That’s what happens to JS files, right?
Aug 13, 2019 at 16:44
@JuanMendes Yes: compile ( tsc ) then run ( node ) = «Run» (as frontend IDE functionality on a perf with «Run» for .js files.
Как настроить компиляцию typescript в webstorm?
Как сделать так что бы в webstorm .ts файлы компилировались в js сразу после изменений.
- Вопрос задан более трёх лет назад
- 858 просмотров
Комментировать
Решения вопроса 1

Знаю больше чем это необходимо

tsconfig должен быть, если нет то вторая галочка, но я ее работу никогда не проверял
Ответ написан более трёх лет назад
Комментировать
Нравится Комментировать
Ответы на вопрос 1
frontend-разработчик
Не надо завязываться на редактор. Настройте webpack — он будет частью вашего проекта и будет доступен вне зависимости от окружения. Статей, роликов и других материалов навалом — гугл в помощь.
Ответ написан более трёх лет назад
Нравится 1 1 комментарий
