Skip to content

Commit 6123083

Browse files
committed
workflow(preinstall): add preinstall script
1 parent 6e688ee commit 6123083

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@
5454
"test-unit": "vitest run",
5555
"coverage": "vitest run --coverage",
5656
"release": "esno ./scripts/release.mts",
57-
"preinstall": "node -e \"if (process.env.INIT_CWD === process.cwd()) { process.exit(1) }\" || npx only-allow pnpm",
57+
"preinstall": "node -e \"if (process.env.INIT_CWD === process.cwd()) { process.exit(1) }\" || esno ./scripts/preinstall.mts",
5858
"postinstall": "node -e \"if (process.env.INIT_CWD === process.cwd()) { process.exit(1) }\" || npx simple-git-hooks"
5959
},
6060
"peerDependencies": {

scripts/preinstall.mts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import fs from 'node:fs'
2+
import spawn from 'cross-spawn'
3+
4+
declare const process: NodeJS.Process
5+
6+
function convertVersion(dependencies) {
7+
let isConverted = false
8+
for (const k in dependencies) {
9+
if (dependencies[k].startsWith('^') || dependencies[k] === '*') {
10+
dependencies[k] = 'latest'
11+
isConverted = true
12+
}
13+
}
14+
return isConverted
15+
}
16+
17+
async function preinstall() {
18+
// 仅限开发环境
19+
if (process.env.INIT_CWD === process.cwd()) {
20+
// 配置 git 钩子
21+
spawn.sync('npx', ['only-allow', 'pnpm'], { stdio: 'inherit' })
22+
23+
// 安装依赖前,将依赖的版本号替换为 latest
24+
// 只会替换 ^* 和 *,如果需要指定某些依赖的版本,可以使用波浪号,或直接锁死
25+
// 一方面是保持 git diff 的干净清爽,另一方面是保持依赖不过时
26+
// 版本号的变更记录用 lock 文件来追踪
27+
const pkg = JSON.parse(fs.readFileSync('./package.json', 'utf-8'))
28+
const { dependencies, devDependencies } = pkg
29+
30+
const isDependenciesConverted = convertVersion(dependencies)
31+
const isDevDependenciesConverted = convertVersion(devDependencies)
32+
33+
if (isDependenciesConverted || isDevDependenciesConverted) {
34+
fs.writeFileSync('./package.json', JSON.stringify(pkg, null, 2))
35+
}
36+
}
37+
}
38+
39+
try {
40+
preinstall()
41+
} catch (e) {
42+
console.error(e)
43+
}

0 commit comments

Comments
 (0)