1. 程式人生 > >npm 5 package-lock.json 坑坑坑!!

npm 5 package-lock.json 坑坑坑!!

前幾天升級了 Node.js v8.0 後,自帶的 npm 也升級到了5.0,第一次使用的時候確實驚豔到了:原本重新安裝一次模組要十幾秒到事情,現在一秒多就搞定了。先不要激動,現在我來大概講一下 npm 5 的一些大的變化:

  • 使用npm install xxx命令安裝模組時,不再需要--save選項,會自動將模組依賴資訊儲存到 package.json 檔案;
  • 安裝模組操作(改變 node_modules 資料夾內容)會生成或更新 package-lock.json 檔案
  • 釋出的模組不會包含 package-lock.json 檔案
  • 如果手動修改了 package.json 檔案中已有模組的版本,直接執行npm install
    不會安裝新指定的版本,只能通過npm install [email protected]更新

重新安裝模組之所以快,是因為 package-lock.json 檔案中已經記錄了整個 node_modules 資料夾的樹狀結構,甚至連模組的下載地址都記錄了,再重新安裝的時候只需要直接下載檔案即可(這樣看起來 facebook 的 yarn 好像沒有啥優勢了)。以下是 package-lock.json 檔案的例子:

  1. {
  2. "name": "test_pkg_lock",
  3. "version": "1.0.0",
  4. "lockfileVersion": 1,
  5. "dependencies": {
  6. "commander": {
  7. "version": "2.9.0",
  8. "resolved": "https://registry.npmjs.org/commander/-/commander-2.9.0.tgz",
  9. "integrity": "sha1-nJkJQXbhIkDLItbFFGCYQA/g99Q="
  10. },
  11. "cssfilter": {
  12. "version": "0.0.8",
  13. "resolved": "https://registry.npmjs.org/cssfilter/-/cssfilter-0.0.8.tgz",
  14. "integrity": "sha1-ZWTKzLqKdt2bS5IGaLn7f9pQ5Uw="
  15. },
  16. "graceful-readlink": {
  17. "version": "1.0.1",
  18. "resolved": "https://registry.npmjs.org/graceful-readlink/-/graceful-readlink-1.0.1.tgz",
  19. "integrity": "sha1-TK+tdrxi8C+gObL5Tpo906ORpyU="
  20. },
  21. "xss": {
  22. "version": "0.2.18",
  23. "resolved": "https://registry.npmjs.org/xss/-/xss-0.2.18.tgz",
  24. "integrity": "sha1-bfX7XKKL3FHnhiT/Y/GeE+vXO6s="
  25. }
  26. }}

帶來速度的同時,npm 也挖了個大大的坑:

以後直接改 package.json 檔案相應模組的版本號,再執行npm install不會更新了(好可怕),你只能手動用npm install [email protected]指定版本號來安裝,然後它會自動更新 package-lock.json 檔案。直接執行npm install時,如果不存在 package-lock.json 檔案,它會根據安裝模組後的 node_modules 目錄結構來建立;如果已經存在 package-lock.json 檔案,則它只會根據 package-lock.json 檔案指定的結構來下載模組,並不會理會 package.json 檔案。

網上已經有很多人反應這個問題了:GitHub 上的 issue:package-lock.json file not updated after package.json file is changed連結:https://github.com/npm/npm/issues/16866

clean project with some deps in package.json.you run npm imodules are installed and package-lock.json file is created.say you update module A in package.json file.you run npm i. I would expect this updates the package-lock.json file but it doesn’t. which results in module A not being updated.

文章:Understanding lock files in NPM 5連結:http://jpospisil.com/2017/06/02/understanding-lock-files-in-npm-5.html

這裡是 npm 文件關於 package-locks 的說明連結:https://docs.npmjs.com/files/package-locks