Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run npm script with nodemon command

I am testing GraphQL Server from Apollo and what to integrate nodemon to it. Here's sample file structure :

build/
src/
server.js

Here my npm scripts looks like this

"scripts": {
   "start": "babel --presets es2015,stage-2 server.js -d build/  &&  node build/server.js",
   "dev": "nodemon server.js" // Sample code here
}

What npm run start would do is to convert ES6 code into build/server.js using babel and execute it. This would start the server correctly.

What I want is to watch for changes in server.js or in src/ and restart the server if changes occur. Here I want to execute npm run start command if any changes occur. What is the correct 'nodemon' command to my need. Its better if I could use npm run dev like command to start development using nodemon.

like image 339
udarabibile Avatar asked Nov 09 '22 04:11

udarabibile


1 Answers

you can use gulpjs to watch any changes in specific folders and then command it to do something. With your sample, you want to convert the code to es6 too. so it also need gulp-bable and . you can include babel-preset-stage-2 if you want. So you can simply put the code below in gulpfile.js

gulp.task('build-es2015', () => {
    return gulp.src('server.js')
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(gulp.dest('build'));
});
gulp.task('watch', () => {
    gulp.watch(['./app/*.js'], ['build-es2015'])
})

Basically, the task 'watch' will keep watching the specific files. When they are saved then it will to execute the task 'build-es2015' to convert to es6.

And then nodemon, it needs gulp-nodemon then you can do on gulpfile.js

gulp.task('server', () => {
  nodemon({
    script: 'build/server.js',
    ext: 'js',
    ignore: [
      'server.js',
      'node_modules/**',
      'test/**',
      'build/**'
    ]
  })
  .on('restart', () => { console.log(`Server restarted!`) })
})

The above will keep watching build/server.js'. whenever it is changed, nodemon will automatically restart the server.

And the last piece for gulpfile.js

gulp.task('dev', ['server', 'watch'])

Include the tasks that need to be executed for gulp command.

$ gulp dev

or with npm command

"scripts": {
  "start": "gulp dev"
}

so you can npm run start as well.

And dont forget to require all packages in gulpfile.js

const gulp       = require('gulp')
const babel      = require('gulp-babel')
const nodemon    = require('gulp-nodemon')
like image 195
PunNeng Avatar answered Nov 15 '22 06:11

PunNeng