Skip to content

Instantly share code, notes, and snippets.

@riskers
Last active November 28, 2019 18:27
Show Gist options
  • Save riskers/d2097976c012a982e2119ed2fed14689 to your computer and use it in GitHub Desktop.
Save riskers/d2097976c012a982e2119ed2fed14689 to your computer and use it in GitHub Desktop.
check node_modules and yarn.lock match

yarn.lock 与 node_modules 保持一致

  • yarn add xxx 添加新的 package,同时更新 package.jsonyarn.lock
  • yarn upgrade xxx 更新 package,同时更新 package.jsonyarn.lock

这样操作过后,我们把 yarn.lock push 到代码仓库中

node_modules 与 yarn.lock 保持一致

团队使用 Yarn 来管理模块依赖,这样只能保证大家的 yarn.lock 是一致的,但不能保证大家的 node_modules 是一致的(因为 node_modules 并不在版本库里)。要是有人升级了模块,别人拿到了新的 yarn.lock ,但是本地的 node_modules 里的模块仍然是旧的。

本来,团队小伙伴在更新代码到本地后,看到 git 提示 yarn.lock ,然后 yarn install 更新代码,这是正规操作。但是不能保证他一定会 yarn install,比如他忘了或者疏忽了。这样他的 yarn.lockpackage.json 是最新的,但是他本地的 node_modules 里的包却是旧的,这样在本地开发时,可能会导致一些莫名的 bug 。

yarn check --integrity 命令可以检查 node_modules 里模块版本是否和 yarn.lock 一致。用 yarn 安装后, node_modules 里会有一个 .yarn-integrity 文件,里面是一串 hash 值,这串 hash 值是与 yarn.lock 对应的。所以,我们得到了新的 yarn.lock 后,执行这条命令就可以检查 node_modules 里的模块是否也是最新的。

示意图

自动检查

在启动项目的时候检查,可以这样:

// package.json
{
  "scripts": {
    "predev": "yarn check --integrity",
    "dev": "webpack xxx"
  }
}

优化开发体验

为了输出体验,我们可以使用 shelljs 来包装 yarn check --integrity 这条命令,见 yarn_check_node_modules.js

/**
* 检查 node_modules 与 yarn.lock 是否匹配
* 避免因他人更新 yarn.lock 而本地 node_modules 没有更新情况
*
* date:2017-07-19
*/
var shell = require('shelljs');
var colors = require('colors')
shell.exec('yarn check --integrity', {async: true}, function(status) {
if(status != 0) {
shell.echo(colors.red('==========='))
shell.echo(colors.red('node_modules 与 yarn.lock 中版本不匹配'))
shell.echo(colors.red('请执行 yarn upgrade 命令更新包'))
shell.echo(colors.red('==========='))
shell.exit(1)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment