-
Notifications
You must be signed in to change notification settings - Fork 434
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: generate start and test NPM scripts (#303)
- Loading branch information
Showing
3 changed files
with
53 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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 |