Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用 npm 脚本钩子 #20

Open
maomao1996 opened this issue May 31, 2021 · 0 comments
Open

使用 npm 脚本钩子 #20

maomao1996 opened this issue May 31, 2021 · 0 comments
Labels
nodejs nodejs 相关 偷懒系列 开发中偷懒技巧

Comments

@maomao1996
Copy link
Owner

maomao1996 commented May 31, 2021

使用 npm 脚本钩子

钩子说明

npm 脚本中有 prepost 两个钩子

比如 build 脚本命令的钩子就是 prebuildpostbuild

{
  "scripts": {
    "prebuild": "echo I run before the build script",
    "build": "vue-cli-service build",
    "postbuild": "echo I run after the build script"
  }
}

当用户执行 npm run build 时会按如下顺序执行

npm run prebuild && npm run build && npm run postbuild

默认钩子

  • prepublish postpublish
  • preinstall postinstall
  • preuninstall postuninstall
  • preversion postversion
  • pretest posttest
  • prestop poststop
  • prestart poststart
  • prerestart postrestart

注意

  1. 自定义的脚本命令也可以加上 prepost 钩子
    比如 deploy 也有 predeploypostdeploy 钩子

  2. 双重的 prepost 无效,
    比如 prepretestpostposttest

相关资料

npm scripts 使用指南

实战 —— 检测并更新依赖包

当公司内部维护的 npm 包升级时,可能会因为各种原因导致业务使用方更新不及时,这时我们可以在业务项目中编写 npm 脚本钩子,在执行 start 脚本时对这些 npm 包做检测并更新

添加 pre 脚本

scripts 目录下新建 checkDependence.js,并写入如下代码

这里用 dayjsaxios 举栗

const child_process = require('child_process')
const semver = require('semver')
const chalk = require('chalk')

const pkg = require('../package.json')

const { log } = console
const NAME_ARRAY = ['dayjs', 'axios']

// 获取最新版本号
const getLatestVersion = (name) => {
  return child_process.execSync(`npm view ${name} version`, {
    encoding: 'utf8'
  })
}

// 获取本地版本号
const getLocalVersion = (name) => {
  const version = pkg.dependencies[name]
  if (version) {
    return pkg.dependencies[name].replace(/\^|~/g, '')
  }
  log(chalk.yellow(`还没有安装 ${name} 哦`))
  return '0.0.0'
}

for (const name of NAME_ARRAY) {
  const latest = getLatestVersion(name)
  if (semver.gt(latest, getLocalVersion(name))) {
    log(chalk.blue(`正在安装 ${name}@${latest}`))
    child_process.exec(`npm i ${name}`)
  } else {
    log(chalk.green(`已安装最新的 ${name}@${latest}`))
  }
}

修改 package.jsonscripts

{
  "scripts": {
    ...
+   "prestart": "node ./scripts/checkDependence.js"
  }
}

使用效果

npm 相关命令说明

  1. npm view <name> 查询并返回指定包的所有信息
  2. npm view <name> versions 查询并返回指定包的所有版本信息(数组格式)
  3. npm view <name> version 查询并返回指定包的最新版本号

相关资料

npm-view

@maomao1996 maomao1996 added nodejs nodejs 相关 偷懒系列 开发中偷懒技巧 labels Jun 1, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
nodejs nodejs 相关 偷懒系列 开发中偷懒技巧
Projects
None yet
Development

No branches or pull requests

1 participant