-
Notifications
You must be signed in to change notification settings - Fork 398
/
addNpmScript.ts
33 lines (31 loc) · 1.22 KB
/
addNpmScript.ts
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
import * as fs from 'node:fs'
/**
* Adds a new NPM script to the generated package.json file.
* The new script invokes another existing script with the package manager used by the developer,
* and is placed directly after the referenced NPM script.
* @param {string} scriptName the name of the new NPM script
* @param {string} packageManager the name of the used package manager, e.g. npm, pnpm or yarn
* @param {string} invokedScriptName the name of the invoked NPM script
* @param {string} packageJsonPath the path of the destination package.json file
*/
function addNpmScript(
scriptName: string,
packageManager: string,
invokedScriptName: string,
packageJsonPath: string
) {
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))
const command =
packageManager === 'npm'
? `npm run ${invokedScriptName}`
: `${packageManager} ${invokedScriptName}`
packageJson.scripts = Object.entries(packageJson.scripts).reduce((result, entry) => {
result[entry[0]] = entry[1]
if (entry[0] === invokedScriptName) {
result[scriptName] = command
}
return result
}, {})
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2) + '\n')
}
export default addNpmScript