kdub1312
kdub1312

Reputation: 905

How to chain multiple commands in npm package.json scripts

I am trying to create a script in my package.json file that will launch my nodemon app, then trigger a gulp sass watch

Currently, I can do this by running a npm launch which starts nodemon, then in a separate terminal window I can run gulp watch to trigger the sass watch from my gulp file.

I would like to create a single script command in package.json that will do both of these- is that possible?

package.json

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon app.js",
    "launch": "nodemon app.js && gulp watch"
  },

gulpfile.js

const { src, dest, watch } = require("gulp");
const sass = require('gulp-sass')(require('node-sass'));

function generateCSS(cb) {
    src('./sass/**/*.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(dest('public/css'));
    cb();
}

function watchFiles(cb) {
    watch('sass/**/**.scss', generateCSS);
}

exports.css = generateCSS;
exports.watch = watchFiles;

edit: please see my answer below for what worked for me, inspired by the answer from @cmgchess

Upvotes: 4

Views: 11008

Answers (3)

kdub1312
kdub1312

Reputation: 905

per @cmgchess answer in the comments, it turns out using a double ampersand runs the command sequentially. however, there is also the option to use a single ampersand, which will run them in parallel. In this case, this is what I needed:

"launch": "nodemon app.js & gulp watch"

edit: ok the first time I ran the launch it worked fine. however, subsequent launches crashed. I have it working again now over multiple launches, and what I had to do additionally is switch the order of the commands:

"launchreverse": "gulp watch & nodemon app.js"

Upvotes: 2

JLRishe
JLRishe

Reputation: 101778

You should be able to use the npm-run-all package and its run-p command to execute multiple scripts side-by side:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon app.js",
    "watch": "gulp watch",
    "launch": "run-p start watch"
},

Then you can just do:

npm launch

Upvotes: 2

Deyan Petrov
Deyan Petrov

Reputation: 170

Just use the &&

package.json

"build": "npm run base && npm run utilities:global && npm run utilities:unstyled && npm run utilities:styled && npm run components && npm run merge:unstyled && npm run merge:styled && npm run rtl && npm run prejss && npm run themes && npm run full",

Upvotes: 2

Related Questions