Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use nodemon in npm scripts to build and start scripts?

"scripts": {
  "build": "babel src -d lib",
  "start": "node --use_strict ./lib/index.js",
  "watch": "nodemon lib/index.js --exec npm run build"
}

Using the command npm run watch results in the following wrong command being run: [nodemon] starting "npm lib/index.js run build"

How would I write a nodemon command that, on reload, transpiles the code using babel and reloads the code?

like image 711
Connorelsea Avatar asked Apr 24 '16 21:04

Connorelsea


2 Answers

  "scripts": {
    "build": "babel src -d lib",
    "start": "node --use_strict ./lib/index.js",
    "watch": "nodemon --exec \"npm run build && node lib/index.js\" -e js --ignore lib/"
  }

Then run npm run watch. After this, nodemon will rebuild the project and then restart the server every time source code(.js files) is modified.

--exec specifies what non-node scripts (also works for node scripts as above node lib/index.js) you want nodemon to execute when there is a file change.

-e specifies what file extensions you want nodemon to watch.

--ignore specifies the files/directories you want nodemon to ignore. This option is essential to solve this problem because if you do not specify to ignore this lib/ folder, nodemon will restart infinitely as the compiled files in lib/ are also .js files.

like image 170
fishstick Avatar answered Sep 21 '22 02:09

fishstick


You could simply run your code with babel-node to avoid explicit transpiling.

$ nodemon lib/index.js --exec babel-node --presets=es2015,stage-2

It seems like this is the recommended way to use nodemon with babel.

Please note, running --exec could have unintended side effects when running your development environment remotely of your localhost

like image 36
Роман Парадеев Avatar answered Sep 22 '22 02:09

Роман Парадеев