heroku - npm postinstall脚本根据enviro运行grunt任务

js_*_*rog 3 heroku node.js npm gruntjs

我有两个heroku node.js应用程序,一个用于prod,一个用于dev,我还有一个具有dev和prod特定任务的Gruntfile.我知道你可以设置package.json来运行grunt作为npm的postinstall挂钩,但是你可以指定不同的任务来运行,具体取决于你所在的enviro吗?

这是我的package.json的相关部分到目前为止的样子:

"scripts": {
    "postinstall": "./node_modules/grunt/bin/grunt default"
},
Run Code Online (Sandbox Code Playgroud)

如果NODE_ENV是生产等,我不想每次都运行grunt默认值,而是喜欢运行"grunt production".

这可能吗?

qub*_*yte 6

可悲的是,没有像postInstallpostInstallDev.您可以创建一个中间脚本来处理差异.例如,如果您有以下内容:

"scripts": { "postinstall": "node postInstall.js" },
Run Code Online (Sandbox Code Playgroud)

然后在此脚本中,您可以检查环境变量并从那里执行正确的Grunt任务:

// 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);
Run Code Online (Sandbox Code Playgroud)

几个与外围相关的要点......

  • 尽量不要让Grunt和co.作为dependencies.保持它们以devDependencies避免必须在生产中安装所有这些东西.如上所述在vanilla Node中使用中间脚本将允许您执行此操作.我喜欢使用像这样的postInstall脚本来安装git hook脚本(但也只在开发环境中).
  • 你不必使用./node_modules/grunt/bin/grunt default.如果grunt-clidependency或者devDependency,npm知道在哪里看,并且grunt default会正常工作.