How to deploy node app that uses grunt to heroku

ValeriiVasin picture ValeriiVasin · Dec 9, 2012 · Viewed 28.4k times · Source

I'm using grunt and also grunt plugins like grunt-contrib-copy, grunt-contrib-mincss (that listed as npm dependencies for my application).

Also I don't commit npm_modules folder and public folder, where all generated files are. And I can't figure out how to build my app (I have grunt build command) after deploy and setup my server (it's already looking for public folder).

I saw some stuff like grunt-heroku-deploy, but it seems me a bad idea to commit before upload. Maybe there are some gentle decisions... Any thoughts?

Answer

smithclay picture smithclay · Dec 10, 2012

npm has a support for a postinstall step (among many others) that might be just what you're looking for.

The node.js heroku buildpack runs this command when you push to heroku to resolve build dependencies:

$ npm install --production

https://devcenter.heroku.com/articles/nodejs-support#build-behavior

If you take a look at the npm documentation, you can setup a series of scripts to run either before or after anyone runs npm install for your package. It's configured in the scripts property of package.json. The scripts property allows to run custom scripts (including grunt) when certain things happen in a package's lifecycle.

For example, to echo some text and run the grunt command whenever anyone (including Heroku) runs npm install, add this to your package.json:

{
  ...
  "scripts": {
    "postinstall": "echo postinstall time; ./node_modules/grunt-cli/bin/grunt <your task name>"
  },
  ...
}

https://npmjs.org/doc/scripts.html

Important caveats:

  • You might have to change the path to the grunt binary in the postinstall script, check the error output if the grunt command doesn't execute.
  • grunt and grunt-cli must be listed as a dependency in your package.json so it gets installed by Heroku. Listing them under devDependencies is not sufficient since Heroku won't install those. Also, note that Heroku won't install it as a global package so to execute it on Heroku you're going to have to use a relative path (as it is configured above).

If this doesn't work (you'll probably need to fiddle with the relative paths a bit), then you might want to consider writing your own custom buildpack for Heroku.

Update

As of 0.4, the grunt package no longer contains the grunt binary, which is now part of the grunt-cli package. The answer has been updated to reflect this.