An Introduction to Package JSON Scripts in Node.js (2024)

In my experience with modern-stack JavaScript projects and Node.js, the package.json file has been a ubiquitous presence. It serves as the manifest for the project, containing vital information about applications, modules, packages, and more. Beyond being a mere configuration repository, it acts as a central hub for npm, housing the names and versions of all installed packages. Mastering the essential properties of package.json fromNode JS courseis a key to leveraging its power for automation and efficient project management in Node.js.

Understanding the intricacies of package.json scripts has been instrumental in streamlining my Node.js workflow. From defining project dependencies to specifying scripts for various tasks, each property plays a crucial role in shaping the project's structure and behavior. Through hands-on experience and continuous learning, I've come to appreciate the versatility and efficiency that package.json brings to Node.js development.

An Introduction to Package JSON Scripts in Node.js (1)

Most Automations and unrelated actions can be boiled down to the scripts section of the package.json file.

Ever wondered what scripts are? What are they used for? What should we know about it, and what cool things can we do with it? If yes, let me give you a kickstart introduction to effectively using package.json Scripts arguments with Node.js and NPM.

package.json Scripts: An Overview

An npm script is a convenient way to bundle common shell commands like a set of built-in and custom scripts for your project. They are typically terminal commands or a string of terminal commands that help automate repetitive tasks.

In short, NPM scripts are terminal commands that perform a set of actions.

In a project, scripts are stored in a section of the package.json file, which means they are shared amongst everyone using the codebase, ensuring that everyone is using the same command with similar flags.

Their purpose is to provide an effortless way to execute repetitive tasks, like:

  • Running a linter tool on your code
  • Executing the tests
  • Starting your project locally
  • Building your project
  • Minify or Uglify JS or CSS (Cascading Style Sheets)

These scripts can be used effortlessly in CI/CD pipeline to simplify tasks like building and generating test reports.

Using the NPM (Node Package Manager) scripts is also simple. To define an NPM script, set its name and write the script under the ‘scripts’ property of your package.json file:

An Introduction to Package JSON Scripts in Node.js (2)

To execute your Script, use the ‘npm run <NAME-OF-YOUR-SCRIPT>’ command. Some predefined aliases convert to npm run, like npm test or package json npm start, you can use them interchangeably.

Maintaining commands you run regularly as an npm script is common, like starting your application, linting, building production apps, etc.

Example for an NPM Script

A simple example for an NPM script would be:

1. "scripts": { 2.  "scss": "node-sass --output-style compressed -o dist/css src/scss"3. }4.  5. 6. Terminal Command to run the Scriptnpm run scss …… run scss ……

Get a deeper understanding of the Node.is file system module.

Benefits of Using Package JSON Scripts in NodeJS

1. Simplification

  • It streamlines command execution for common tasks (start, test, build, deploy).
  • It eliminates the need to memorize complex commands.

2. Consistency

  • It ensures uniform execution across different environments and developers.
  • It maintains consistent dependency management.

3. Shareability

  • It facilitates easy project setup and task execution for new developers.
  • It promotes collaboration and knowledge transfer.

4. Automation

  • It Simplify complex workflows and repetitive tasks.
  • It Enhances efficiency and minimizes errors.

5. Flexibility

  • It customizes scripts to specific project needs and workflows.
  • It adapts to evolving project requirements.

CommonlyUsed Package JSON Scripts in NodeJS

We have the following Nodejs scripts that every front-end developer should know:

  1. start: Launches the server or application (e.g., "node index.js").
  2. test: Executes project tests (e.g., "jest" or "mocha").
  3. build: Compiles and prepares production-ready code (e.g., "webpack").
  4. dev: Starts a development server withlive-reloading(e.g., "nodemon").
  5. lint: Enforces code style guidelines (e.g., "eslint").

Additionaluseful scripts in NodeJS to write better and more readable code:

We can use the following script for enhanced, improved, and highly readable code:

  1. pre/post scripts: Execute tasks before/after primary scripts (e.g., "prestart", "posttest").
  2. clean: Removes generated files (e.g., "dist" folder).
  3. deploy: Automates deployment processes.

How to Manage Node.js package.json?

Understanding how the package.json file works helps us manage and maintain it better. 

As the name suggests, it is primarily a JSON file, so it needs to be a valid JSON. This means that any missing commas, unclosed quotation marks, or other formatting errors will prevent npm from interacting with it.

It is recommended that you use the npm CLI (Command Line Interface) to update and manage your package to avoid accidental errors and ease the process of managing your dependencies.

Always use `npm init` to initialize your package.json file, as it will ensure you generate a valid one.

Dependencies are best managed using different script commands like ‘npm install,’ npm uninstall, and npm update, so the package.json and node_modules/ folder are kept in sync. 

Manually listing a dependency in the package file does not immediately reflect the state of our node_modules/ folder as our package.json file only records dependencies, and our node_modules/ folder is where the actual code for dependencies is installed. Therefore, it is needed that you run ‘npm install’ before the dependency is installed in your project.

That is why it is easier to use npm to help manage dependencies. It updates both the package file and node_modules folder together.

That said, even though it is not suggested, you can always edit your package file manually in your code editor and then make changes. 

Various commands and scripts you want to be exposed can be specified here, and to discover all the available scripts, you can use the `npm run` command

An Introduction to Package JSON Scripts in Node.js (3)

Several built-in scripts are present in a Package.json script file in addition to their pre-set life cycle events and arbitrary scripts. Let us look into some of them below.

If you are a beginner and want more information, you can go for a Full-stack certification.

Pre and Post Scripts

Let us begin with understanding what npm does when you run a script.

Number one on its checklist is to check the package.json file to see if you have defined a value for that script. If a value matching the script tag is found, it then checks for two other versions of the same script, that is, a ‘pre’ version and a ‘post’ version.

These scripts can be handy for many scenarios like the commands that need to be run before or after a set of actions performed in a project.

If either of these scripts is found, it will run them as the specified script.

A good example would be a command for deleting test logs before running the tests and running a linter afterward.

The creation of "pre" or "post" scripts is easy, these scripts can be defined in the "scripts" section with a matching name and adding "pre" or "post" to the beginning of them.

An Introduction to Package JSON Scripts in Node.js (4)

Let us take an example of such a script

npm run prepare should do the following

  • Run before the package is packed (i.e., during npm publish and npm pack)
  • Automatically run on local npm install without any arguments
  • Should also run AFTER prepublish, but BEFORE prepublishOnly
  • As of npm@7 these scripts run in the background. To see the output, run with: --foreground-scripts.

There are respectively pre- and post-hooks for a lot of commands. This comes in very handy to manage the life cycle of your application.

Life Cycle Scripts

Life Cycle Scripts can be considered special scripts that happen only in certain situations. These scripts work in addition to the pre<event>, post<event>, and <event> scripts.

Examples of life cycle hooks can be prepare, prepublish, prepublishOnly, prepack, and postpack.

An Introduction to Package JSON Scripts in Node.js (5)

Let us suppose if this is what npm was to find in our package.json file, it will run the scripts in the order prestart, start, then poststart. All we would be doing to trigger this is typing `npm start` in the command line. 

These kinds of scripts are beneficial for various situations where something is needed to happen immediately before or immediately after a primary action. 

If we set up our scripts properly, simply running the command npm start will handle all our needs in the proper order.

The same behavior also applies to built-in commands. You can read more about those lifecycle scripts in the npm docs.

NPM Script Options

In some cases, there can be a need to get some extra juice out of your NPM scripts, in these cases, you can pass options to the command you are using in your npm script by adding a -- --flag like in the example below.

Let us see a few examples:

{    "scripts": {        "lint": "eslint .",        "test": "jest ./test",    }} 

If I wanted to run only the tests that changed, the command would be like this:

> npm run test -- --onlyChanged 

And if you wanted to run the linter and save the output in a file, you could execute the following command:

> npm run lint -- --output-file lint-result.txt

User and Environment

  • User:When npm runs with root privileges, scripts are always run with the effective uid and gid of the working directory owner. To overcome this, you should set the unsafe-perm flag to run scripts with root privileges.
  • Environment:Scripts run in different environments where many pieces of information are made available regarding the setup of npm and the current state of the process.
  • Exit:Scripts are run by passing the line as a script argument to sh, and if it exits with a code other than 0, then this aborts the process.

Note that these script files do not have to be Node.js or JavaScript programs. They only must be some sort of executable file.

Creating Custom Package JSON Scripts [Step–by–Step]

A. Passing Arguments to Package JSON Scripts

  • Open package.json: Locate the "scripts" property within the file.
  • Add a new script: Define a custom script name and its associated command.

package.json script example:

"scripts": {"my-custom-script": "node my-script.js"}

B. package.jsonRunning Multiple Scripts in Parallel

1. Useprocess.argv: Access command-line arguments within scripts usingprocess.argv.

Example:

// my-script.jsconsole.log(process.argv); // Output: ['node', 'my-script.js', 'arg1', 'arg2']

2. Run with arguments:npmrun my-custom-script arg1 arg2

3. Utilize npm-run-all: Install thenpm-run-allpackage:npminstallnpm-run-all --save-dev

4. Define a combined script:

{ "parallel-tasks": "npm-run-all --parallel task1 task2"}

Best Practices for Writing Package JSON Scripts

Front end developers and engineers must follow the below listed best practicesin order todeliver highly maintainable, readable and bug free code:

  • Keep it simple: Break down complex tasks into smaller scripts.
  • Meaningful names: Use descriptive names to understand script's purpose.
  • Avoid hardcoding: Store paths and values in environment variables.
  • Use dependencies: Let NPM handle installation instead of scripts.
  • Modularize scripts: Extract reusable logic into separate functions.
  • Handle errors: Exit gracefully on failures for clear feedback.
  • Document it: Add comments explaining what each script does.
  • Pre/post scripts:Utilizethem for setup/cleanup before/after main scripts.
  • Test our scripts: Ensure they behave as expected in different scenarios.
  • Review and refine: Regularly maintain and improve our scripts.

By following these tips,we’llwrite clean, efficient, and maintainable scripts thatbenefitour development workflow.

Looking to enhance your coding skills? Dive into the world of Python with our online python certification course. Unleash your potential and become a Python pro today!

Conclusion

Checking out this concise introduction to the principles around npm scripts should help you in your development workflow and make it easier to evaluate the package.json scripts you come across. Hopefully, you will revisit this post when you begin developing your own scripts. If you have any further questions, I recommend you look through the FAQs below or check out npm's well-written documentation, starting with the npm CLI docs. A Better set of resources can be found at KnowledgeHut’s Node.js tutorial and projects course. For next steps, check out our blog posts about how to check installed npm package version in node.js.

An Introduction to Package JSON Scripts in Node.js (2024)
Top Articles
Paytm Customer Support Help Centre
NEFT vs RTGS: What is the Difference Between NEFT and RTGS?
No Hard Feelings (2023) Tickets & Showtimes
Mcgeorge Academic Calendar
Evil Dead Rise Showtimes Near Massena Movieplex
Teamexpress Login
Brutál jó vegán torta! – Kókusz-málna-csoki trió
Bc Hyundai Tupelo Ms
Walmart Windshield Wiper Blades
Otterbrook Goldens
Tcu Jaggaer
Procore Championship 2024 - PGA TOUR Golf Leaderboard | ESPN
Michael Shaara Books In Order - Books In Order
Dignity Nfuse
Niche Crime Rate
Pretend Newlyweds Nikubou Maranoshin
Lehmann's Power Equipment
TBM 910 | Turboprop Aircraft - DAHER TBM 960, TBM 910
Td Small Business Banking Login
라이키 유출
Hobby Stores Near Me Now
Catherine Christiane Cruz
Georgia Cash 3 Midday-Lottery Results & Winning Numbers
Drug Test 35765N
If you have a Keurig, then try these hot cocoa options
Prot Pally Wrath Pre Patch
Hobby Lobby Hours Parkersburg Wv
1636 Pokemon Fire Red U Squirrels Download
Craigslist Northern Minnesota
Ocala Craigslist Com
Nurofen 400mg Tabletten (24 stuks) | De Online Drogist
Inmate Search Disclaimer – Sheriff
A Grade Ahead Reviews the Book vs. The Movie: Cloudy with a Chance of Meatballs - A Grade Ahead Blog
Roadtoutopiasweepstakes.con
Minecraft Jar Google Drive
Telegram update adds quote formatting and new linking options
Alpha Asher Chapter 130
Giovanna Ewbank Nua
814-747-6702
Lucifer Morningstar Wiki
2Nd Corinthians 5 Nlt
Thothd Download
Brown launches digital hub to expand community, career exploration for students, alumni
Darkglass Electronics The Exponent 500 Test
Unit 11 Homework 3 Area Of Composite Figures
Joy Taylor Nip Slip
Christie Ileto Wedding
Parks And Rec Fantasy Football Names
Divisadero Florist
How to Find Mugshots: 11 Steps (with Pictures) - wikiHow
Unity Webgl Extreme Race
Latest Posts
Article information

Author: Duane Harber

Last Updated:

Views: 6137

Rating: 4 / 5 (51 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Duane Harber

Birthday: 1999-10-17

Address: Apt. 404 9899 Magnolia Roads, Port Royceville, ID 78186

Phone: +186911129794335

Job: Human Hospitality Planner

Hobby: Listening to music, Orienteering, Knapping, Dance, Mountain biking, Fishing, Pottery

Introduction: My name is Duane Harber, I am a modern, clever, handsome, fair, agreeable, inexpensive, beautiful person who loves writing and wants to share my knowledge and understanding with you.