最新消息:

操蛋的 npm 5 package-lock.json 坑

node admin 11047浏览 0评论

前几天升级了 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 xxx@yy更新

重新安装模块之所以快,是因为 package-lock.json 文件中已经记录了整个 node_modules 文件夹的树状结构,甚至连模块的下载地址都记录了,再重新安装的时候只需要直接下载文件即可(这样看起来 facebook 的 yarn 好像没有啥优势了)。以下是 package-lock.json 文件的例子:

{
  "name": "test_pkg_lock",
  "version": "1.0.0",
  "lockfileVersion": 1,
  "dependencies": {
    "commander": {
      "version": "2.9.0",
      "resolved": "https://registry.npmjs.org/commander/-/commander-2.9.0.tgz",
      "integrity": "sha1-nJkJQXbhIkDLItbFFGCYQA/g99Q="
    },
    "cssfilter": {
      "version": "0.0.8",
      "resolved": "https://registry.npmjs.org/cssfilter/-/cssfilter-0.0.8.tgz",
      "integrity": "sha1-ZWTKzLqKdt2bS5IGaLn7f9pQ5Uw="
    },
    "graceful-readlink": {
      "version": "1.0.1",
      "resolved": "https://registry.npmjs.org/graceful-readlink/-/graceful-readlink-1.0.1.tgz",
      "integrity": "sha1-TK+tdrxi8C+gObL5Tpo906ORpyU="
    },
    "xss": {
      "version": "0.2.18",
      "resolved": "https://registry.npmjs.org/xss/-/xss-0.2.18.tgz",
      "integrity": "sha1-bfX7XKKL3FHnhiT/Y/GeE+vXO6s="
    }
  }}

带来速度的同时,npm 也挖了个大大的坑:

以后直接改 package.json 文件相应模块的版本号,再执行npm install不会更新了(好可怕),你只能手动用npm install xxx@yy指定版本号来安装,然后它会自动更新 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

转载请注明:爱开源 » 操蛋的 npm 5 package-lock.json 坑

您必须 登录 才能发表评论!