heroku — npm postinstall script to run grunt task depending on enviro

房东的猫 提交于 2019-12-06 07:49:34

问题


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?


回答1:


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.



回答2:


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.



来源:https://stackoverflow.com/questions/21634349/heroku-npm-postinstall-script-to-run-grunt-task-depending-on-enviro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!