
Если у вас еще нет проекта, давайте создадим его с нуля
- Создайте новую папку проекта
$ mkdir node-api-ts
2. Заходим в созданную папку проекта и инициализируем npm в проекте
$ cd node-api-ts # this initializes npm and creates a new file called package.json with defaults $ npm init -y
3. Создайте папку src и файл index.ts внутри
$ mkdir src && cd src && touch index.ts && cd ..
Теперь давайте реализуем Typescript в проекте.
- Убедитесь, что на вашем компьютере установлен Typescript
# this tells you what version of Typescript you have installed $ tsc -v # for example my version is 5.0.2 $ Version 5.0.2 # if you don't get a version number is because is not installed yet # so lets install it globally on your computer with this command $ npm i -g typescript # then check again if it gives you the version with tsc -v
2. Инициализируйте Typescript в своем проекте
# this will create a tsconfig.json file in your root folder $ tsc --init
3. Обновите некоторые свойства в файле tsconfig.json
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"rootDir": "./src", /* this is so that it listens to our src */
"outDir": "./build", /* this is the folder with the compiled js code */
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
4. Добавьте пакеты NPM в проект
# install express and cors $ npm i express cors # the -D will install this package into the devDependencies $ npm i ts-node @types/express @types/cors -D
5. Давайте настроим проект на использование type: module, чтобы мы могли использовать импорт, а не требовать использования пакетов NPM.
# in package.json add the following line "type": "module",

6. Теперь добавим код в файл index.ts
// src/index.ts
// minimal Express API
import express, { Request, Response } from 'express'
import cors from 'cors'
const app = express()
app.use(cors())
app.use(express.json())
app.get('/', (req: Request, res: Response) => {
res.json({ greeting: 'Hello world!' })
})
app.listen(4000, () => console.log('api listening on PORT ', 4000))
9. Давайте вручную запустим компилятор машинописного текста, который в основном создает папку сборки и генерирует .js файлов из .ts файлов.
# run the typescript compiler with $ tsc
7. Нодемон установлен?
# check if you have nodemon installed with: $ nodemon -v # if it does not gives you a version number then install it with: $ npm i -g nodemon
10. Наконец, давайте добавим скрипт start в package.json, который позволит Nodemon прослушивать изменения .TSfiles.
"scripts": {
"start": "nodemon --exec ts-node-esm ./src/*.ts",
Теперь вы сможете слушать свои файлы .ts с помощью
npm run start
и это должно выглядеть так:

Теперь любые изменения, которые вы вносите в свои .ts файлы, Nodemon будет отслеживать эти изменения.
Наслаждайтесь 🍻