heroku — npm postinstall script to run grunt task

2019-04-11 18:40发布

I've got two heroku node.js apps, one for prod and one for dev, and I also have a Gruntfile with dev- and prod-specific tasks. I know you can set up package.json to run grunt as a postinstall hook for npm, but can you specify somehow different tasks to be run depending on what enviro you're in?

Here's what the relevant section of my package.json looks like so far:

"scripts": {
    "postinstall": "./node_modules/grunt/bin/grunt default"
},

Rather than run grunt default every time, I'd love to run "grunt production" if NODE_ENV is production, etc.

Is this possible?

2条回答
甜甜的少女心
2楼-- · 2019-04-11 19:06

Sadly there's no difference like postInstall and postInstallDev. You can make an intermediate script to handle the difference though. For example, if you have the following:

"scripts": { "postinstall": "node postInstall.js" },

Then in this script you could check the environment variable and execute the correct Grunt task from there:

// postInstall.js
var env = process.env.NODE_ENV;

if (env === 'development') {
    // Spawn a process or require the Gruntfile directly for the default task.
    return;
}

if (env === 'production') {
    // Spawn a process or require the Gruntfile directly to the prod task.
    return;
}

console.error('No task for environment:', env);
process.exit(1);

A couple of peripherally related points...

  • Try not to have Grunt and co. as dependencies. Keep them to devDependencies to avoid having to install all that stuff in production. Having an intermediary script in vanilla Node like the above will allow you to do this. I like to use a postInstall script like this to install git hook scripts too (but also only on development environments).
  • You don't have to use ./node_modules/grunt/bin/grunt default. If grunt-cli is a dependency or devDependency, npm knows where to look and grunt default will work fine.
查看更多
对你真心纯属浪费
3楼-- · 2019-04-11 19:12

For some reason, my dev environment was never running my "development" if statement. I sent a ticket to Heroku support, and this was their answer: "By default, your environment is not available during slug compilation. If you would like to make this available, you can enable an experimental feature called "user-env-compile". Please see the following article for details: http://devcenter.heroku.com/articles/labs-user-env-compile". Good to know. So, I went another route using the heroku-buildpack-nodejs-grunt buildpack, and then creating a heroku:development grunt task.

查看更多
登录 后发表回答