如何通过Grunt运行节点脚本?

时间:2017-03-27 21:44:50

标签: node.js gruntjs

我希望通过我的gruntfile运行一个node命令。我只需要跑:

node index.js

作为任何其他任务之前的第一项任务。我试着四处寻找,但还没有找到答案。我相信它可能很简单,但我不确定如何。我需要加载nmp任务吗?

这就是我的Gruntfile的样子:

"use strict";

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    jshint: {
      all: [
        'Gruntfile.js'
      ],
      options: {
        jshintrc: '.jshintrc',
      },
    },

    // Before generating any new files, remove any previously-created files.
    clean: {
      tests: ['dist/*']
    },

    // Configuration to be run (and then tested).
    mustache_render: {
      json_data: {
        files: [
          {
            data: 'jsons/offer.json',
            template: 'offers.mustache',
            dest: 'dist/offers.html'
          },
          {
            data: 'jsons/profile.json',
            template: 'profile.mustache',
            dest: 'dist/profile.html'
          }
        ]
      }
    }
  });


  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-mustache-render');

  // Whenever the "test" task is run, first clean the "tmp" dir, then run this
  // plugin's task(s), then test the result.
  grunt.registerTask('default', ['clean', 'jshint', 'mustache_render']);


};

我想在“清理”任务之前运行“node index.js”。

1 个答案:

答案 0 :(得分:4)

执行此操作的标准方法是使用grunt-run task

执行:

npm install grunt-run --save-dev

在你的咕噜文件中:

grunt.loadNpmTasks('grunt-run');

然后是一些配置(来自文档):

grunt.initConfig({
  run: {
    options: {
      // Task-specific options go here.
    },
    your_target: {
      cmd: 'node',
      args: [
        'index.js'
      ]
    }
  }
})

然后您将任务注册更改为:

grunt.registerTask('default', ['run', 'clean', 'jshint', 'mustache_render']);