Npm后安装只在开发

我有npm模块与以下package.json

{ "name": "my-app", "version": "0.0.0", "scripts": { "prepublish": "bower install", "build": "gulp" }, "dependencies": { "express": "~4.0.0", "body-parser": "~1.0.1" }, "devDependencies": { "gulp": "~3.6.0", "bower": "~1.3.2" } } 

当我将我的应用程序部署到生产环境时,我不想安装devDependecies,因此运行npm install --production 。 但是在这种情况下, prepublish脚本被调用,但是它并不需要,因为我在生产中使用CDN链接。

如何仅在npm install后调用postinstall脚本,而不是在npm install --production后调用npm install --production

我认为你不能根据--production参数来select运行哪些脚本。 但是,您可以执行的操作是提供一个testingNODE_ENVvariables的脚本,并且只在非“生产”时才运行bower install

如果你总是处于unix-y环境,你可以这样做:

 { scripts: { "prepublish": "[ \"$NODE_ENV\" != production ] && bower install" } } 

这只适用于类似unix的环境:

当使用–production运行安装时,NPM将环境variables设置为“true”。 要仅运行postinstall脚本(如果npm install未与–production一起运行),请使用以下代码。

 "postinstall": "if [ -z \"$npm_config_production\" ]; then node_modules/gulp/bin/gulp.js first-run; fi", 

我使用windows,osx和linux工作,所以我使用了一个NON环境特定的解决scheme来解决这个问题:

postinstall处理程序中,我执行一个检查process.env.NODE_ENVvariables的js脚本并完成工作。

在我的具体情况下,我只能在开发环境中执行gulp任务:

package.json的一部分

 "scripts": { "postinstall": "node postinstall" } 

所有的postinstall.js脚本

 if (process.env.NODE_ENV === 'development') { const gulp = require('./gulpfile'); gulp.start('taskname'); } 

最后一行gulpfile.js

 module.exports = gulp; 

从gulpfile.js中导出gulp非常重要,因为所有任务都在特定的gulp实例中。

解决scheme是依赖于你的shell的unix性质:

  "scripts": { "postinstall": "node -e \"process.env.NODE_ENV != 'production' && process.exit(1)\" || echo do dev stuff" },