How to transform a npm script to a grunt task?

2019-05-21 03:11发布

问题:

I have the following script with my nodeJS.

"scripts": {
    "start": "grunt",
    "test": "node --debug --harmony node_modules/grunt-cli/bin/grunt test"
}

I am running node v0.11.13 so I need to set --harmony flag. On grunt the tests are configured right if I start them with npm test, but I would prefer to have it all in a gruntfile. Is there a way to configure grunt to start the server and also run the test ?

回答1:

You can create an alias task that spawns grunt with those node flags, like such:

grunt.registerTask('debug', function() {
  var done = this.async();
  // Specify tasks to run spawned
  var tasks = Array.prototype.slice.call(arguments, 0);
  grunt.util.spawn({
    // Use the existing node path
    cmd: process.execPath,
    // Add the flags and use process.argv[1] to get path to grunt bin
    args: ['--debug', '--harmony', process.argv[1]].concat(tasks),
    // Print everything this process is doing to the parent stdio
    opts: { stdio: 'inherit' }
  }, done);
});

Then you can start the server and run tests with: grunt default debug:test

Or really any combination:

  • grunt server test (runs both without node flags)
  • grunt debug:server:test (runs both with node flags).