-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
104 lines (98 loc) · 2.76 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const cwd = process.cwd()
// console.log(`Current directory: ${process.cwd()}`);
const path = require('path')
const fs = require('fs')
const targz = require('targz');
const { getHash } = require('./utils/get-hash')
const util = require('util')
const exec = util.promisify(require('child_process').exec);
const targetProjectRootPath = cwd;
const packageJsonFilePath = path.resolve(targetProjectRootPath, 'package.json')
const cacheHashFilePath = path.resolve(targetProjectRootPath, '.node_modules_hash.json')
const log = console.log
function updateHashCache(hashes) {
const maxCacheCount = 100
if (hashes.length > maxCacheCount) {
hashes = hashes.slice(hashes.length - maxCacheCount)
}
return fs.writeFileSync(cacheHashFilePath, JSON.stringify(hashes, null, 4))
}
function readJson(file) {
let result
if (fs.existsSync(file)) {
const str = fs.readFileSync(file, {
encoding: 'utf-8'
})
try {
result = JSON.parse(str);
} catch (e) {
}
} else {
log(`${file} not exist!`)
}
return result
}
/**
* 检测package.json依赖包是否变化
*/
function detectNodeModuleDependencies() {
const hashes = readJson(cacheHashFilePath) || []
const packageJSON = readJson(packageJsonFilePath) || {}
const depsContent = JSON.stringify({
dependencies: packageJSON.dependencies,
devDependencies: packageJSON.devDependencies
})
log('cacheHashFilePath', cacheHashFilePath)
const hash = getHash(depsContent)
const lastHash = hashes[hashes.length - 1]
function updateHash() {
hashes.push(hash)
updateHashCache(hashes)
}
return new Promise((resolve, reject) => {
if (!lastHash) {
log('你好像是第一次执行build, 打包node_modules...')
resolve(updateHash)
} else if (hash !== lastHash) {
log('检测到依赖项发生变化,打包node_modules...')
resolve(updateHash)
} else {
log('检测到与上次执行时相比较,依赖项无变化,不需要重新打node_modules依赖包')
resolve()
}
})
}
/**
* 打包node_modules
* @param {*} successCb
*/
function packNodeModules(successCb) {
log('packNodeModules')
targz.compress({
src: path.resolve(targetProjectRootPath, 'node_modules'),
dest: path.resolve(targetProjectRootPath, 'node_modules.tar.gz'),
}, function(err) {
if (err) {
throw err
} else {
successCb && successCb()
process.exit()
}
});
// exec('tar -czf node_modules.tar.gz node_modules').then(() => {
// console.log('node_modules.tar.gz ready!')
// successCb && successCb()
// process.exit()
// }, (err) => {
// throw err
// })
}
detectNodeModuleDependencies().then((updateHash) => {
if (updateHash) {
packNodeModules(updateHash)
} else {
process.exit()
}
}, (err) => {
throw err
})