node.jsnpmgulp

Automatic run gulp tasks via npm


I usually run gulp via npm, e.g. in my package.json

"scripts": {
    "test": "gulp test",
    "minify": "gulp minify"
}

Then I can run command such as

npm run minify

Which is okay, but every time I've new tasks in my gulpfile, I need to add them to the package.json under the scripts section, is there any better way to do so?

Reason: I only install npm globally to my path so all other modules will not pollute my path, so I need to run them via npm scripts


Solution

  • Have I got a treat for you: I went ahead and made you a simple npm module to handle this.

    gulp-npm-script-sync

    Here is the gist of it:

      var file = fs.readFileSync(config.path || 'package.json', 'utf-8');
      var pkg = JSON.parse(file);
      var tasks = gulp.tasks;
    
      pkg.scripts = pkg.scripts || {};
    
      Object.keys(tasks).forEach(function (t) {
        pkg.scripts[t] = 'gulp '+tasks[t].name;
      });
    

    The full source does stuff like write the package.json back with the same indention and stuff.

    So yeah go ahead: npm install --save-dev gulp-npm-script-sync

    Stick this in your gulpfile:

    var gulp = require('gulp');
    var sync = require('gulp-npm-script-sync');
    
    // your gulpfile contents
    
    sync(gulp);
    

    Every time you update your gulpfile with a new task it will update your package.json.

    You can even throw it inside a gulp task:

    gulp.task('sync', function () {
      sync(gulp);
    }