Is it possible to leverage npm scripts to simultaneously execute tsc -watch and nodemon --watch?

Is there a way to simultaneously run `tsc --watch` and `nodemon --watch` using npm scripts? I can execute each command separately, but when trying to combine them in a script, only the first one runs. For example:

"scripts": {    
  "runDeb": "set NODE_ENV=development && tsc --watch && nodemon --watch"
}

When running this script, only `tsc --watch` is executed and `nodemon` is never called, or vice versa.

Answer №1

Here is a sample of what might work for you (based on my current configuration):

"scripts": {
    "build": "gulp build",
    "serve": "node server.js"
}

I've defined two scripts, "build" and "serve". To kickstart your development process, simply run npm run serve which will start the server. If you need to rebuild any assets, you can use the npm run build command.

Although using concurrently could be an alternative approach, I prefer this setup as it ensures that the build task is completed before executing the server.

Answer №2

I have recently made the switch from using AlterX's solution to utilizing tsc-watch and have been impressed by its performance improvement. Tsc-watch allows for incremental compilation, similar to the -w flag, resulting in a much faster restart of the application.

To implement tsc-watch in your project, simply add the following line to your package.json file:

"scripts": {
  "start": "tsc-watch --onSuccess \"node .\""
}

Answer №3

Make sure to include the following in your package.json:

"scripts": {
  "start": "concurrently --kill-others \"tsc -w\" \"nodemon dist/app.js\"",
}

Don't forget to also install these npm packages (concurrently, nodemon, typescript) in your package.json:

"devDependencies": {
  "concurrently": "^2.2.0",
  "typescript": "^1.8.10",
  "nodemon": "^1.9.2",
}

Answer №4

How things are unfolding

The issue at hand involves the presence of two watchers overseeing all the files. One is operating as tsc -w, while the other is functioning as nodemon.

Whenever a modification is made to a file with a .ts extension, tsc detects it, compiles the changes, and generates the corresponding .js version in your specified destination folder.

From the perspective of Nodemon, there are multiple alterations being noticed—one for the .ts file and another one for the newly created .js file. Upon detecting the first change, Nodemon restarts itself automatically. However, upon sensing the second change, it mistakenly attempts to restart again, resulting in a failure. This seems to be a flaw within nodemon – more details can be found at https://github.com/remy/nodemon/issues/763.

Possible Resolutions

1) Utilize tsc-watch --onSuccess

tsc-watch features the --onSuccess option, where you can incorporate node. This method ensures the presence of just one watcher.

2) Implement a Delay for nodemon

You have the ability to postpone nodemon restarts easily (refer to --delay). This solution necessitates minimal adjustments.

3) Restrict nodemon's Monitoring to TSC's Destination Folder Only

Although initial setup issues may arise, configuring nodemon to monitor solely the destination folder produced by TSC could potentially resolve the problem of multiple detections. Nevertheless, this approach might pose challenges in the future or when tsc generates numerous files.

Answer №5

My approach in October of 2018 utilizing the latest versions of nodemon.

Step one:
Firstly, you need to install nodemon (npm install nodemon --save-dev) and ts-node (npm install ts-node --save-dev).

Step two:
Next, create a nodemon.json. I prefer keeping my nodemon configuration separate in a nodemon.json file to make npm scripts easier to understand. Create the nodemon.json in the project root with the following contents:

{
    "ignore": ["**/*.test.ts", "**/*.spec.ts", ".git", "node_modules"],
    "watch": ["src"], // your .ts source folder
    "exec": "npm start", // your npm script defined in package.json
    "ext": "ts"
}

After that, set up your npm start script like this:

"scripts": {
    ...
    "start": "ts-node src/server.ts",
    "dev:ts": "nodemon",
    ...
  }

Now, running npm run dev:ts or yarn dev:ts will execute and monitor your TypeScript server code.

To explore additional configurations like setting up Jest unit tests, refer to this article.

Answer №6

The TypeScript-Node-Starter is known for its high speed and efficiency.

Check out the GitHub repository here

"dev": "concurrently -k -n \"TypeScript,Node\" -c \"yellow.bold,cyan.bold\" \"npm run watch-ts\" \"nodemon ./dist/app.js\"",
"watch-ts": "tsc -w"

In this setup, npm run watch-ts has been labeled with the name TypeScript using concurrently -n, while also being highlighted in color yellow.bold through concurrently -c.

This configuration allows for easy identification of messages from each process running simultaneously.

Answer №8

If you're looking for an alternative approach, consider including the sleepcommand in your concurrently setup before launching nodemon.

For example:

"scripts": {
    "dev": "concurrently -k \"tsc -p ./src/server -w\" \"tsc -p ./src/client -w\" \"sleep 5 && nodemon ./dist/server/server.js\"",
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node ./dist/server/server.js"
  },

In my case, initializing both client and server TypeScript projects simultaneously led to nodemon starting up 3 times when I ran npm run dev. By introducing a brief pause with the sleep command before launching nodemon, I ensured that both tsc processes had completed their tasks, improving efficiency.

An alternative option could be utilizing the delay feature of nodemon, but personally, I only required the initial delay when running npm run dev. Subsequent recompilations trigger nodemon correctly without additional delays.

Note: If your server's performance is sluggish, consider extending the sleep duration beyond 5 seconds.

I also experimented with the recommended solution, but found that my custom approach yielded faster results during subsequent recompilations while keeping nodemon and tsc watch processes active.

With my method, there was only a 1-second delay compared to the accepted answer's 5-second delay. The key difference was ensuring that tsc operated in watch mode as intended, preventing full recompiles with every change in either TypeScript project.

Answer №9

In summary; Use nodemon to monitor changes in the output of tsc (specifically, the .js files).

You should configure nodemon to watch for the completion of tsc --watch, as mentioned in other comments. Simply instruct it to observe the output directory of tsc for alterations in .js files.

For instance, in your package.json:

"scripts": {
  ...
  "watch": "tsc --build src/tsconfig.json --watch",
  "watch-tests": "nodemon --watch dist -e js --exec \"yarn run tests\"",
  "tests": "some script to run my tests",
  ...
}

and in your src/tsconfig.json:

{
...
  "compilerOptions": {
    "outDir": "../dist",
    ...
  },
...
}

Where

  • --watch <folder> corresponds to the directory specified in your compilerOptions->outDir from the tsconfig.json file,
  • -e js focuses on changes within javascript files, and
  • --exec <some arbitrary thing to run>
    enables nodemon to manage tasks beyond node.js scripts.

If you want to execute a node script using nodemon, you can simplify it to

nodemon --watch dist -e js my-node-script.js

Note: To prevent nodemon from triggering its script too quickly, utilize the throttle delay option with --delay

Answer №10

Running files with a .ts extension is made easy with the use of ts-node. By installing it globally, you can seamlessly integrate ts-node into your workflow, allowing tools like nodemon to automatically utilize it.

Answer №11

Traditional compilation process:

When the file is named main.ts

Step 1: tsc main.ts

Step 2: node main.js

For easy and one-time compilation:

tsc main --watch

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In tsconfig.json, the compiler is not utilizing other tsconfig.json files when using the "extends"

I'm attempting to streamline my project by breaking up my tsconfig.json into separate files. I have one for the source files and another for the tests. However, when I utilize the extends field, it seems that only the base tsconfig.json is being utili ...

How can I retrieve List<T> from a Razor Page using TypeScript?

Within my ViewModel, I have an Items collection: public class ItemViewModel{ public List<Item> Items {get;set;} } In the Index.cshtml file: @if(Model.Items != null){ <li><a id="item-id-link" href="#" data-items="@Model.Items"> ...

NPM encountered an issue with error code E401, stating "Failed to authenticate, authentication required: Basic realm="GitHub""

Encountering an issue with node v10.15.1 and npm v6.14.15 When trying to run npm install in the project's root folder, I am faced with the following error: npm ERR! code E401 npm ERR! Unable to authenticate, need: Basic realm="GitHub" npm ...

Is there a way to fix an npm install error without having to remove my package-lock.json file?

I encountered an issue while working on a project in create-react-app and attempting to install react-router-dom. Unfortunately, the installation failed with the following error message: npm ERR! Cannot read property 'match' of undefined Many ot ...

Retrieve the response type from a Prisma FindUnique query

Essentially, my goal is to determine the type of the result obtained from a FindUnique operation in Prisma. The current return type is any: import prisma from "@/libs/prismaDb"; import { Prisma } from "@prisma/client"; export default a ...

When clicking the button, the service function is not properly updating the view

Upon calling this.getLeaderboard(); in the ngOnInit() function within leaderboard.component.ts, the leaderboard is only displayed on page load or refresh, which is expected. However, I also want to retrieve and display the leaderboard upon clicking a butto ...

Issue encountered in NestJS with Prisma: When trying to invoke the class constructor t without using 'new', an error occurs stating that it

I've been attempting to establish a Prisma client within my NestJS application, but I keep encountering this persistent error: [Nest] 14352 - 12.05.2023, 23:21:13 ERROR [ExceptionHandler] Class constructor t cannot be invoked without 'new&apos ...

Cookie Compliance Notification appearing on each website

I'm currently working on implementing a cookie consent feature using the component found at https://github.com/tinesoft/ngx-cookieconsent. The information does display on the site, but even after agreeing, it keeps reappearing upon refresh. I understa ...

The RC-dock library's 'DockLayout' is not compatible with JSX components. The instance type 'DockLayout' is not a valid JSX element and cannot be used as such

Despite encountering similar questions, none of the provided answers seem to address the issue within my codebase. My project utilizes React 17, Mui v5, and TS v4. I attempted to integrate a basic component from an external package called rc-dock. I simply ...

npm not working to install packages from the package.json file in the project

When using my macbook air, I encounter an issue where I can only install npm packages globally with sudo. If I try to install a local package without the -g flag in a specific directory, it results in errors. npm ERR! Error: EACCES, open '/Users/mma ...

Is there a way to retrieve the chosen value from a select element?

How do I retrieve the chosen value from a select element? In my select.component.ts file: export class PfSelectComponent implements OnInit { constructor() { } ngOnInit() { } @Input() options : Array<Object>; } Contents of select.compon ...

Guide on utilizing map function and reassigning the value

I am facing a challenge with a list of books that have IsEnable defaulting to False. During onInit(), I need to check each book to see if it is enabled. I was considering using an rxjs map and calling the getEligibleBooks() function within the map, but I ...

Tips for setting up a hierarchical mat-table within a parent table that supports expandable rows using Angular Material

Here is the data that I am working with: [ { "_id": "c9d5ab1a", "subdomain": "wing", "domain": "aircraft", "part_id": "c9d5ab1a", "info.mimetype": "application/json", "info.dependent": "parent", ...

"Encountering a 'npm command not found' error despite having Node successfully

A while back, I successfully installed node and npm using Homebrew. However, today I am encountering the frustrating npm command not found error. After typing $ whereis node, I receive no results. Upon entering $ which node, I see that /usr/local/bin/nod ...

Jest is raising a TypeError: Unable to access attributes of an object that is undefined (referencing 'getVideoTracks')

When running my unit tests with Jest, I encountered an error: TypeError: Cannot read properties of undefined (reading 'getVideoTracks') Does anyone have any suggestions on how to properly test the following line using Jest? [videoTrack] = (await ...

Make sure to always include a trailing comma when defining a single type parameter T. Here's an example: `<T,>`

Ensure that a single type parameter T includes a trailing comma. For example: <T,>. (3:29) export const toggleItem = <T>( How can I resolve this error? Adding <T,> causes Prettier to remove the "," when saving. I have not made any change ...

The TypeScript type definition for reduce is used to aggregate values in

What is the best way to properly declare a type for this scenario? interface MediaQueryProps { [key: string]: number; } const size: MediaQueryProps = { small: 576, medium: 768, large: 992, extra: 1200 }; export default Object.keys(size).reduce ...

Using 'import' and 'export' in Ionic 2 requires specifying 'sourceType: module'

Starting a new project using Ionic 2 and encountering an error after installing angular2-jwt: ParseError: 'import' and 'export' may appear only with 'sourceType: module' D:\desenv\arquivos\workspace_inbit&bsol ...

Encountered a problem while trying to retrieve HTML values from an object within a ReactJS component

I have encountered an issue while working with an object that contains HTML values. When trying to access it, I am facing the following error: Element implicitly has an 'any' type because expression of type 'any' can't be used to ...

Control the transparency of the initial parent div that includes an *ngFor loop

I want to add opacity only to the first div which contains an icon and a heading in another nested div. The second div should remain fully visible (opacity: 1). Here is the HTML structure: <div class="row clearfix"> <div class="col-lg-3 col- ...