UNPKG

2.08 kBJavaScriptView Raw
1'use strict'
2
3const cwd = process.cwd()
4const path = require('path')
5const fs = require('fs-extra')
6const { error, info } = require('./utils/log')
7const npmVersions = require('./utils/check-npm-version')
8const { getNodeModulesDir } = require('./env')
9const { installFromScripts } = require('./index')
10
11const nodeModulesDir = getNodeModulesDir()
12const scriptPath = path.join(__dirname, '../scripts/postinstall')
13const destDirPath = path.join(nodeModulesDir, '.hooks')
14const destScriptPath = path.join(destDirPath, 'postinstall')
15
16/**
17 * 检查 npm 版本
18 *
19 * npm 使用 npm-lifecycle 执行 hooks,但是某些版本存在 bug
20 * https://github.com/npm/npm-lifecycle/pull/13/files
21 *
22 * 规则: npm-lifecycle 存在,且版本 < 2.0.2,报错并提示用户升级 npm,具体规则链接到 README
23 *
24 * @returns {void}
25 */
26function checkNpm () {
27 /**
28 * CI 环境下不执行,不然单元测试会报错,系统测试前会单独检测并升级 npm
29 */
30 if (process.env.CI) {
31 return
32 }
33
34 const { npmVersion, npmLifecycleVersion, pass } = npmVersions
35
36 info(
37 `npm version: ${npmVersion}`,
38 `npm-lifecycle version: ${npmLifecycleVersion || '-'}`
39 )
40
41 if (!pass) {
42 error(
43 'elint 在当前的 npm 版本下无法正常运行,请升级 npm 后再安装',
44 '更多信息请访问:http://t.cn/Rg7xvP0'
45 )
46
47 process.exit(1)
48 }
49}
50
51/**
52 * 安装 npm hooks
53 *
54 * @returns {void}
55 */
56function installHooks () {
57 // 开发过程中不执行
58 if (!cwd.includes('node_modules')) {
59 return
60 }
61
62 // 确保目录存在
63 fs.ensureDirSync(destDirPath)
64
65 // 部署 scripts
66 fs.copySync(scriptPath, destScriptPath)
67
68 // 兼容 windows
69 if (process.platform === 'win32') {
70 const cmdScriptPath = path.join(__dirname, '../scripts/postinstall.cmd')
71 const destCmdScriptPath = path.join(destDirPath, 'postinstall.cmd')
72
73 fs.copySync(cmdScriptPath, destCmdScriptPath)
74 }
75
76 // 添加执行权限
77 fs.chmodSync(destScriptPath, 0o755)
78}
79
80checkNpm()
81
82installHooks()
83
84// 安装完成执行一次 install
85installFromScripts()