Skip to content
DeveloperMemos

Adding a Script to a package.json File

Node.js, package.json, scripts1 min read

A package.json file is a common part of any Node.js project. It's a JSON file that contains metadata about the project, including a list of dependencies and scripts that can be run as part of the project.

One useful feature of the package.json file is the ability to define custom scripts that can be run from the command line. This can be helpful for automating tasks or setting up a workflow for your project.

To add a script to your package.json file, you'll need to open the file in a text editor and find the "scripts" section. This section is an object where the keys are the names of the scripts, and the values are the commands that should be run when the script is executed.

For example, let's say you want to add a script that runs your tests. You could add the following to your package.json file:

1"scripts": {
2 "test": "jest"
3}

Psst! By the way, I wrote another article a little while back about how to redirect to another page using React. If you're interested feel free to check it out!


Now, you can run your tests by typing npm run test on the command line.

You can also pass arguments to your scripts by appending them after the script name. For example, npm run test -- --coverage would run your tests and generate a coverage report.

It's also possible to chain scripts together by using the && operator. For example, you might have a script that lints your code and then runs your tests:

1"scripts": {
2 "test": "eslint . && jest"
3}

In this case, the eslint command will be run first, and if it succeeds, the jest command will be run.

You can add as many scripts as you like to your package.json file, and they can be as simple or complex as you need them to be. This can be a helpful way to streamline your workflow and automate common tasks. Just remember to use descriptive names for your scripts so it's easy to understand what they do.