2012-03-11 85 views
13

我有一个应用程序,我正在部署到Nodejitsu。最近,他们遇到了npm问题,导致我的应用程序在尝试(并失败)重新启动后几个小时脱机,因为它的依赖关系无法安装。有人告诉我,将来可以避免这种情况,将我所有的依赖项列为bundledDependencies放入我的package.json中,从而导致依赖项与应用程序的其余部分一起上传。这意味着我需要我的package.json看起来是这样的:有没有办法自动生成bundledDependencies列表?

"dependencies": { 
    "express": "2.5.8", 
    "mongoose": "2.5.9", 
    "stylus": "0.24.0" 
}, 
"bundledDependencies": [ 
    "express", 
    "mongoose", 
    "stylus" 
] 

现在干的理由,这是不吸引人。但更糟糕的是维护:每次添加或删除依赖项时,我都必须在两个地方进行更改。有没有我可以用来同步bundledDependenciesdependencies的命令?

+0

PING :)这是回答您的问题还是有其他东西要解决? – wprl 2013-01-24 04:57:11

回答

10

如何执行grunt.js任务来完成它?这工作:

module.exports = function(grunt) { 

    grunt.registerTask('bundle', 'A task that bundles all dependencies.', function() { 
    // "package" is a reserved word so it's abbreviated to "pkg" 
    var pkg = grunt.file.readJSON('./package.json'); 
    // set the bundled dependencies to the keys of the dependencies property 
    pkg.bundledDependencies = Object.keys(pkg.dependencies); 
    // write back to package.json and indent with two spaces 
    grunt.file.write('./package.json', JSON.stringify(pkg, undefined, ' ')); 
    }); 

}; 

假如把它放在你的项目的根目录下一个名为grunt.js文件。要安装grunt,请使用npm:npm install -g grunt。然后通过执行grunt bundle来捆绑软件包。

一个评注中提到的NPM模块可能是有用的:(我还没有尝试过)https://www.npmjs.com/package/grunt-bundled-dependencies

+0

把你的答案,并提出了一个图书馆.. https://github.com/GuyMograbi/grunt-bundled-dependencies。请考虑添加到您的答案。 – 2016-02-13 17:53:09

0

您可以使用一个简单的Node.js脚本来读取和更新bundleDependencies财产,并通过NPM运行生命周期钩子/脚本。

我的文件夹结构是:

  • scripts/update-bundle-dependencies.js
  • package.json

scripts/update-bundle-dependencies.js

#!/usr/bin/env node 
const fs = require('fs'); 
const path = require('path');  
const pkgPath = path.resolve(__dirname, "../package.json"); 
const pkg = require(pkgPath); 
pkg.bundleDependencies = Object.keys(pkg.dependencies);  
const newPkgContents = JSON.stringify(pkg, null, 2);  
fs.writeFileSync(pkgPath, newPkgContents); 
console.log("Updated bundleDependencies"); 

如果您使用的是最新版本的npm(> 4.0.0) ,你可以使用prepublishOnlyprepack脚本:https://docs.npmjs.com/misc/scripts

prepublishOnly:运行前的包装准备和包装,只有 NPM发布。 (见下文)。

预组装:之前压缩包跑包装(上NPM包,NPM发布和 安装git的依赖时)

package.json

{ 
    "scripts": { 
    "prepack": "npm run update-bundle-dependencies", 
    "update-bundle-dependencies": "node scripts/update-bundle-dependencies" 
    } 
} 

你可以测试你自己通过运行npm run update-bundle-dependencies

希望这会有所帮助!

相关问题