1 //此文件是检查node+npm的版本 在build.js里面使用
2 'use strict'
3 const chalk = require('chalk') //导入chalk模块 用来改变字体颜色
4 const semver = require('semver') //导入semver即语义化版本 用来控制版本
5 const packageConfig = require('../package.json') //导入package.json,用于获取项目需要node+npm的版本
6 const shell = require('shelljs') //导入shelljs模块 用来执行unix命令
7
8 //封装方法 用来获取纯净的版本号
9 //child_process是node用来创建子进程 execSync是创建同步进程
10 function exec(cmd) {
11 return require('child_process').execSync(cmd).toString().trim()
12 }
13
14 //node版本信息
15 const versionRequirements = [{
16 name: 'node', //名称是Node
17 currentVersion: semver.clean(process.version), //当前的node版本号
18 versionRequirement: packageConfig.engines.node //要求的node版本号
19 }]
20
21 if (shell.which('npm')) {
22 // 将npm添加到versionRequirements
23 versionRequirements.push({
24 name: 'npm', //名称是npm
25 currentVersion: exec('npm --version'), //纯净的当前npm版本号
26 versionRequirement: packageConfig.engines.npm //要求的npm版本号
27 })
28 }
29
30 module.exports = function () {
31 const warnings = []
32
33 for (let i = 0; i < versionRequirements.length; i++) {
34 const mod = versionRequirements[i]
35
36 // 如果当前版本号不符合要求的版本号,那么就将提示信息添加到wranings
37 if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
38 warnings.push(mod.name + ': ' +
39 chalk.red(mod.currentVersion) + ' should be ' +
40 chalk.green(mod.versionRequirement)
41 )
42 }
43 }
44
45 // 如果有 warnings 那么就打印出来
46 if (warnings.length) {
47 console.log('')
48 console.log(chalk.yellow('To use this template, you must update following to modules:'))
49 console.log()
50
51 for (let i = 0; i < warnings.length; i++) {
52 const warning = warnings[i]
53 console.log(' ' + warning)
54 }
55
56 console.log()
57
58 //执行失败
59 process.exit(1)
60 }
61 }