Skip to content

Commit 3e8baaa

Browse files
committed
fix(init): update package.json postinstall
1 parent 7387773 commit 3e8baaa

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

src/commands/init.ts

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,22 @@ import { PackageJson } from 'type-fest'
33
import { add } from './add'
44
import { install } from './install'
55

6+
const regex = /^[ ]+|\t+/m
7+
68
export function init(): void {
79
// Read package.json
8-
const pkg = JSON.parse(
9-
fs.readFileSync('package.json', 'utf-8')
10-
) as PackageJson
10+
const str = fs.readFileSync('package.json', 'utf-8')
11+
const pkg = JSON.parse(str) as PackageJson
1112

1213
// Add postinstall script
13-
if (pkg.scripts !== undefined) {
14-
pkg.scripts.postinstall = 'husky install'
15-
}
14+
pkg.scripts ||= {}
15+
pkg.scripts.postinstall = 'husky install'
16+
17+
// Write package.json
18+
const indent = regex.exec(str)?.[0]
19+
fs.writeFileSync('package.json', JSON.stringify(pkg, null, indent))
20+
21+
// Install husky
1622
install()
1723

1824
// Add pre-commit sample

test/init.sh

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,13 @@ init_git
1313
npx --no husky init
1414
npm set-script test "echo \"msg from pre-commit hook\" && exit 1"
1515

16+
1617
# Debug
1718
# cat .husky/*
1819

20+
# Test package.json scripts
21+
grep '"postinstall": "husky install"' package.json || echo -e "\e[0;32mOK\e[m"
22+
1923
# Test core.hooksPath
2024
test_hooksPath ".husky"
2125

0 commit comments

Comments
 (0)