2012-03-11 84 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

希望這會有所幫助!

相關問題