Running 2 async tasks with grunt

2019-04-20 18:47发布

问题:

I am working on a small node project and I use coffeescript and less for client-side code. I am trying to set up my development environment using grunt. I've implemented custom grunt task for running server like this:

start = require './start' #just a function to start express.js application
grunt.registerTask 'server', 'Starting server', ->
    grunt.log.write 'Preparing server to start'
    done = do @async
    start (err) ->
        grunt.log.write "server running at localhost:4000"

I also want to run the "watch" task using grunt-contrib-watch plugin:

grunt.initConfig
    watch:
        coffee:
            files: ['public/coffee/**/*.coffee']
            tasks: ['coffee']
        jade:
            files: ['public/jade/**/*.jade']
            tasks: ['jade']
        less:
            files: ['public/less/**/*.less']
            tasks: ['less']

The question is: How to make this two tasks (watch and server) run simultaneously? I want to have a server up and running and don't want to reload it every time some client-side code is changed. Thanks in advance

回答1:

Prefix it to your watch tasks, and get rid of the done = do @async inside the server task.

tasks: ['server', 'coffee']

You want to specify an option in your Grunt configuration for the server task to be "long-running" or not. Then you can call @async only if you need it to be long running (without the watch task).



回答2:

You can run two or more tasks at the same time using any of these two packages :

  1. grunt-parallel
  2. grunt-concurrent


回答3:

I was having this same issue of not being able to launch both watch and connect server from a grunt task.

To solve the problem, I started the server as background process using grunt-exec in my Gruntfile

The ampersand (&) at the end of grunt connect:preview & is what starts the server as a background process.

,exec: {
  start_server: {
    command: 'grunt connect:preview &'
  }
}

And then register the grunt task like this

grunt.registerTask('preview', ['clean:preview', 'template', 'exec', 'watch' ]);

There's got to be a better way to do this, but so far it's the best I could think of.