Nodemon typescript node js

Debugging NodeJS Typescript App using Nodemon

This configuration will tell TypeScript to compile the TypeScript files to JavaScript, and output the compiled files to the «dist» folder. The «rootDir» field specifies the root folder of your TypeScript source files.

Step 2: Configure nodemon

Create a nodemon.json file in the root folder of your project, and add the following configuration:

 "watch": ["src"], "ext": "ts,json", "ignore": ["src/**/*.spec.ts"], "exec": "ts-node --files --require tsconfig-paths/register src/index.ts" > 

This configuration will tell nodemon to watch the «src» folder for changes, and ignore any test files. The «exec» field specifies the command to run when nodemon restarts the application. The «ts-node» package is used to run the TypeScript files directly, without needing to compile them to JavaScript. The «tsconfig-paths» package is used to handle module resolution when using paths specified in the tsconfig.json file.

Step 3: Start the development server

Start the development server by running the following command in your terminal:

This will start the nodemon process and begin watching for changes to your files.

Step 4: Set up debugging

Open your Node.js TypeScript project folder in your preferred code editor and create a new launch.json file in the .vscode folder. Add the following configuration to the file:

 "version": "0.2.0", "configurations": [  "name": "Debug nodemon", "type": "node", "request": "attach", "restart": true, "protocol": "inspector", "port": 9229, "localRoot": "$/dist", "remoteRoot": "$", "sourceMaps": true, "outFiles": [ "$/dist/**/*.js" ] > ] > 

This configuration will tell your code editor to attach to the nodemon process running the application, and enable debugging using the source maps generated by TypeScript. The «localRoot» field should be set to the folder containing the compiled JavaScript files. The «outFiles» field should be set to the folder containing the transpiled JavaScript files.

Step 5: Start debugging

To start debugging, run the nodemon command in your terminal, and then select the «Debug nodemon» configuration in your code editor’s debug panel. This will attach the debugger to the nodemon process and allow you to set breakpoints and step through your TypeScript code.

Conclusion

Setting up nodemon to debug a Node.js TypeScript application with source code debugging is a simple process that can greatly improve your development workflow. With the right configuration, you can quickly and easily debug your code and ensure that your application is running smoothly. Follow the steps outlined in this article, and you’ll be up and running in no time!

Источник

Node.js Setup With TypeScript, Nodemon and ESM

Let’s try to set up a Node.js/Express.js TypeScript project with nodemon and ESM!

Yesterday someone in the ZTM Discord server asked if it was possible to use nodemon with TypeScript and native ECMAScript modules.

I used Node.js (version 14 works) and a bit of internet sleuthing to figure out how to do it.

TypeScript

Create a new directory. Inside that directory, we’ll need to initialize a new Node.js project:

Now for the dependencies. First, Express.js:

As development dependencies, we use TypeScript, nodemon, ts-node and the necessary types:

npm i --save-dev typescript nodemon ts-node @types/node @types/express 

The above command creates a new file called tsconfig.json . Adjust the following parts in the file:

  "module": "ES2020",  "moduleResolution": "Node",  "outDir": "./dist" > 

Compiled files (from TypeScript to JavaScript) will land in the dist folder.

Add these lines to package.json to enable ECMAScript modules and allow imports from your compiled TypeScript files:

  "type": "module",  "exports": "./dist/index.js" > 

Minimal Server

Let’s create our source code. Make a new folder called src and add a file called index.ts inside that directory.

Here’s a minimal Express server:

import express, < Request, Response >from 'express'  const app = express() const port = 5000  app.get('/', (req: Request, res: Response) =>   res.json(< greeting: 'Hello world!' >) >)  app.listen(port, () =>   console.log(`🚀 server started at http://localhost:$port>`) >) 

Wiring Up Scripts

Now, the magic will come together. Add the following script to package.json :

  "scripts":   "dev:server": "nodemon --watch './**/*.ts' --exec 'node --experimental-specifier-resolution=node --loader ts-node/esm' src/index.ts"  > > 

First, we’ll use nodemon with the —watch flag to keep track of all TypeScript files. We can use —execute to run other scripts.

We use the experimental loader feature with hooks to run ts-node . We need the library so that we can directly run TypeScript on Node.js:

It JIT transforms TypeScript into JavaScript, enabling you to directly execute TypeScript on Node.js without precompiling. This is accomplished by hooking node’s module loading APIs, enabling it to be used seamlessly alongside other Node.js tools and libraries.

Importing Files

You probably want to split up your code into different files and import them.

You cannot import a TypeScript file directly.

That means that you first have to transpile all TypeScript files it into JavaScript and then import the JavaScript files.

Using the node —experimental-specifier-resolution=node in the start command is a first step. Enabling the flag allows you to use the standard import syntax without using a file ending. This works as known:

import < blababla >from './some-folder/some-file' 

I will use tsc-watch to run tsc in watch mode and delegate to nodemon if the compilation is successful.

npm install --save-dev tsc-watch 
  "scripts":   "watch": "nodemon --watch './**/*.' --exec 'node --experimental-specifier-resolution=node --loader ts-node/esm' src/index.ts",  "dev": "tsc-watch --onSuccess \"npm run watch\""  > > 

tsc will write the JavaScript files into the specified outDir location (see tsconfig.json ). We’ve set the folder to ./dist .

In package.json we added an exports key-value-pair which allows us to import those transpiled files from the dist folder as if they were the original TypeScript files.

Let’s say that you have a folder structure like this:

. ├── dist │ ├── index.js │ ├── services │ │ └── accounts │ │ ├── index.js │ │ ├── resolvers.js │ │ └── typeDefs.js │ └── utils │ └── apollo.js ├── node_modules ├── package.json ├── package-lock.json ├── src │ ├── index.ts │ ├── services │ │ └── accounts │ │ ├── index.ts │ │ ├── resolvers.ts │ │ └── typeDefs.ts │ └── utils │ └── apollo.ts └── tsconfig.json 

In src/index.ts you want to import something from src/services/accounts/index.ts . It works like normal JavaScript even though the files are TypeScript files:

// src/index.ts  import < startApolloServer >from './services/accounts/index' 

Node.js will use your configuration to import the according JavaScript file under the hood.

Thoughts

It was a bit tricky to find out how to pair nodemon with the Node.js loader feature. While you’ll get console warnings about using this experimental feature, it works fine on the latest Node.js v14.

Resources

More from the blog

Источник

TypeScript & Nodemon — The Ultimate Setup!

Setting up TypeScript and Nodemon can sometimes get tricky, in this article I am going to show you how to setup TypeScript and Nodemon with ease!

Find the full source code of this article in this github repository

Create a Sample Project

Let’s start by creating a sample project, we’ll do this by running:

mkdir typescript-nodemon-ultimate-setup 

Next, create minimal npm packge by running:

npm init -y or yarn init -y 

Note: to reduce verbosity, for the rest of the article i’m going to use npm and omit yarn commands

Add the required dependencies:

npm i -D typescript ts-node nodemon @types/node 

Initialize TypeScript by running npx tsc —init

Lastly, we need some source code to work with, so let’s create src/index.ts file containing the following TypeScript:

function greet(name: string): void   console.log('Hello', name); >  const readerName = 'Medium Reader';  greet(readerName); 

Adding Nodemon

Nodemon can be configured in various ways, I am going to configure it with a json file by adding nodemon.json in our project root folder:

  "restartable": "rs",  "ignore": [".git", "node_modules/", "dist/", "coverage/"],  "watch": ["src/"],  "execMap":   "ts": "node -r ts-node/register"  >,  "env":   "NODE_ENV": "development"  >,  "ext": "js,json,ts" > 

Let’s go over the configuration:

  • restartable — a command we can use to restart the program manually
  • ignore — list of files we don’t want to trigger a program restart when changing
  • watch — list of paths we do want to trigger a program restart when changing
  • execMap — a mapping between a file type/extension to a runtime
  • env — environment variables to include
  • ext — the file extensions Nodemon monitores

In order to run and debug our setup, add two scripts in package.json file:

  "scripts":   "dev": "nodemon --config nodemon.json src/index.ts",  "dev:debug": "nodemon --config nodemon.json --inspect-brk src/index.ts"  > > 

Note the dev:debug script adds —inspect-brk flag, this tells node to halt the program execution until the debugger is attached, this can be replaced with —inspect flag to debug without halting.

Now we can run our program with npm run dev, try to change something the see the program re runs with the updated code!

Debugging with VSCode

The last piece in this puzzle is adding VSCode debugging configuration.

Create .vscode/launch.json file containing the following configuration:

  "version": "0.2.0",  "configurations": [    "type": "node",  "request": "attach",  "name": "Attach",  "restart": true,  "processId": "$"  >  ] > 

Now when we launch nodemon by npm run dev:debug and the program halts until we attached to it:

After attaching the VSCode will stop on the first line of code and you can easily debug your program!

Источник

Читайте также:  Php with pdo odbc
Оцените статью