有没有办法自动生成 bundledDependencies 列表?

13

我有一个应用程序,我正在将其部署到Nodejitsu。 最近,他们遭遇了npm问题,导致我的应用程序在我尝试(但失败)重新启动它后下线了数小时,因为无法安装其依赖项。 我被告知可以通过在我的package.json中将所有依赖项列为bundledDependencies来避免这种情况发生,从而使依赖项随其他应用程序一起上传。 这意味着我的package.json需要看起来像这样:

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

现在,从DRY的角度来看,这并不令人感到吸引。但更糟糕的是维护:每次我添加或删除一个依赖项时,我都必须在两个地方进行更改。是否有一种命令可以用来将 bundledDependenciesdependencies 同步?


PING :) 这个回答解决了您的问题吗?还是有其他问题需要解决? - wprl
2个回答

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的文件中,并将其放在项目的根目录。使用npm安装grunt:npm install -g grunt。然后执行grunt bundle来捆绑包。

一位评论者提到了一个可能有用的npm模块:https://www.npmjs.com/package/grunt-bundled-dependencies(我没有尝试过)。


将您的答案制作成一个库.. https://github.com/GuyMograbi/grunt-bundled-dependencies。请考虑将其添加到您的答案中。 - guy mograbi

2
您可以使用简单的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发布时,在准备和打包软件包之前运行。(见下文。)

prepack:在打包tarball之前运行(在npm pack、npm publish和安装git依赖项时)。

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

你可以通过运行npm run update-bundle-dependencies来自行测试。
希望这能帮到你!

难道不应该使用bundledDependencies而非pkg.bundleDependencies = Object.keys(pkg.dependencies);吗? - Kid101

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接