package.json Quick Start Guide | phoenixNAP KB (2024)

Introduction

Manual project dependency management is a weary task. For Node.js projects, the package.json file provides a simplified way to manage a project's metadata and dependencies.

The file ensures a project always has current information about the libraries and tools it needs to work correctly.

Learn all about thepackage.jsonfile and its various properties in this guide.

package.json Quick Start Guide | phoenixNAP KB (1)

What is package.json?

Every npm package and Node.js project has apackage.jsonfile with metadata for a project. The file resides in the root directory of every Node.js package and appears after running the npm init command.

package.json Quick Start Guide | phoenixNAP KB (2)

The package.json file contains descriptive and functional metadata about a project, such as a name, version, and dependencies. The file provides the npm package manager with various information to help identify the project and handle dependencies.

package.json Example

The package.json file is fully customizable and looks different for every project. A basic package.json file looks like the following:

{"name": "example-name","version": "1.0.0"}

The example file contains elementary fields suitable for a personal project and the minimum required fields to publish a package.

However, published packages benefit from having a more comprehensive package.json file. For example:

{"name": "example-name","version": "1.0.0","license": "MIT","description": "An example NodeJS project","keywords": ["example", "learning", "kb"],"author": "Bob","contributors": [{"name": "Alice","email": "[email protected]"}],"main": "app.js","repository": {"type": "git","url": "https://github.com/phoenixnap-KB/example.git"},"scripts": {"start": "node index.js","dev": "nodemon"},"dependencies": {"express": "^4.1.4","compression": "~1.3.2"},"devDependencies": {"nodemon": "^1.18.10"}}

The file contains various metadata with package and dependency information. Whether long or short, the package.json file must be a valid JSON file to work correctly.

package.json Metadata

The package.json metadata fields help describe various properties of a Node.js project. The properties divide into two subtypes:

  • Descriptive properties help identify a project and distinguish a package if published.
  • Functional properties install and manage the project and its dependencies correctly.

Below is a brief overview of some commonly used properties in apackage.jsonfile.

name Property

The name property is a descriptive field that identifies a project. The combination of a project name and version forms a unique identifier for a package.

In a package.json file, the name property looks like the following:

"name": "example-name"

Several rules put limitations on the value in the name field:

  • The maximum length of a name is 214 characters.
  • Only lowercase letters are allowed in a name.
  • Hyphens and underscores are allowed, but avoid usingspaces and other characters. The name is a part of a URL, a command line argument, and a directory/folder name. Therefore, the value should respect the naming conventions of all three cases.

For published packages, the name must be unique. Check the npm registry to verify if there is a package with the same name.

version Property

The version property is a descriptive field that helps identify the package version. A published project requires having a version field in the package.json file. If working on a personal project, this property is optional.

The version property looks like this:

"version": "1.0.0"

The version number corresponds to the semantic versioning specifications in the form:

<major>.<minor>.<patch>
package.json Quick Start Guide | phoenixNAP KB (3)

When releasing a new package version, increment:

  • <major> when the changes are not backward compatible.
  • <minor> when the update contains new functionalities which do not break older versions.
  • <patch> when pushing compatible bug fixes.

The version field lets developers know what an update brings and what precautionary measures to take before updating.

For example, a major release informs developers that a package does not work with their current build and will require reworking the code that uses the package before updating.

license Property

The license is an informative field in a package.json file that lets other developers know about restrictions and permissions when using or distributing a package.

The most basic way to use the license property is to provide an SPDX license identifier. For example:

"license": "MIT"

Advanced use cases include using multiple licenses:

"license": "(MIT OR GPL-3.0)"

Alternatively, provide a custom-defined license:

"license": "See license in <file>"

If using a custom license, include the file at the top level of the package.

description Property

The description property is a custom and brief explanation of the project's purpose and function. For example:

"description": "An example Node.js project."

Add a description to help other developers discover the package when listing through npm search.

package.json Quick Start Guide | phoenixNAP KB (4)

For unpublished packages, use the description to write short documentation for the project.

keywords Property

The keywords property has a similar purpose as a description field. The npm package manager indexes the keywords array, which helps developers find packages. A list of keywords looks like the following example:

"keywords": ["example", "learning", "kb"]

The property is beneficial for published packages as it helps others discover the module. Unpublished packages do not benefit from using keywords.

author and contributors Properties

The author and contributor fields properties define the creators and helpers of a project. The author property is a single entity, whereas the contributors property is an array (with none, one, or several entries).

The author and contributor sections have the following fields:

{"name": "First Middle Last","email": "[email protected]","url": "http://my-website.com/about-me"}

Alternatively, shorten the syntax to a single line:

"author": "First Middle Last <[email protected]> (http://my-website.com/about-me)"

The email and URL parameters are optional for both authors and contributors.

main Property

The main property points to the project's entry point. When a Node.js application imports the package through a require statement, the package.json file uses the exports from the file in the main property and returns it to the application.

The syntax for the main property is:

"main": "app.js"

The file path is relative to the root directory of the package. If a package.json file does not have the main property, the value defaults to index.js.

repository Property

The repository property contains information about the repository where the code resides. Use this field to point interested parties to thesource code.

The repository property has the following form:

"repository": {"type": "git","url": "<URL to git repo.git>","directory": "<path to package.json>"}

The URL is the publicly available repository. If the package.json file is not in the root directory, state the directory path in the directory field.

scripts Property

The scripts property in a package.json file contains commands that run at various times in the package lifecycle. The key-value pairs have the script name and the corresponding user-made script or command to execute.

An example scripts property looks like the following:

"scripts": {"start": "node index.js""dev": "nodemon"}

To run scripts defined in the scripts property, use the default npm run command:

npm run <script name>

Scripts are a simple and powerful tool for building and maintaining projects. Use the property to streamline commands for building, testing, and developing a module.

dependencies Property

The dependencies property is an essential field in a package.json file. The section maps production-level dependent packages and their versions used in the project.

An example dependencies property is:

"dependencies": "{"<package name>": "^4.1.4","<package name>": "~1.3.2","<package name>": "1.0.2","<package name>": "<=1.3.2"}

Additional characters help define advanced version ranges. The syntax for versioning comes from the node-semver package. The package is available as an npm dependency which you can install with:

npm install semver

Import the package as a module or use it as a command-line utility to double-check a version number.

devDependencies Property

The devDependencies property defines the package dependencies necessary for the development process. The development dependencies help other developers copy the build steps.

For example, if a package.json file contains a development script that uses the nodemon tool for monitoring, add the devDependencies field and provide the compatible version:

"scripts": {"start": "node index.js""dev": "nodemon"},"devDependencies": {"nodemon": "^1.18.10"}

UsedevDependenciesto list unnecessary packages for production but aid in creating a development environment that is true to the original setup.

optionalDependencies Property

The optionalDependencies property in a package.json file lists dependencies that are not essential for the package to work.

If the packages in the property are available, they are installed and provide additional functionalities. Add packages to this section in cases where:

  • A package is only available on some systems.
  • The specific package version is only available on some systems.
  • Developers who use the package can choose not to install the packages.

Compared to other dependencies, the main difference with theoptionalDependenciesproperty is that the package works correctly without the provided dependencies.

The optionalDependencies property uses the same syntax as dependencies and devDependencies. The names of packages map to version numbers or ranges inside a list.

engines Property

The engines property in a package.json file describes the Node.js version and other runtime environments compatible with the package.

The object maps runtime environment names to version numbers or ranges. For example:

"engines": { "node": "~14.0.0", "npm": "5.0.0"}

Defining the engines property in a package.json file lets developers and package users know the specific runtime environments where the package works correctly. Different runtime environments do not guarantee a package's functionality and can produce behavior other than expected.

os Property

The os property lists the operating systems a package runs on. For example:

"os": ["ubuntu", "debian"]

Alternatively, use the property to block operating systems:

"os": ["!darwin", "!win23"]

If the package.json file does not have the os property, the package is compatible with every operating system.

cpu Property

The cpu property defines the CPU architecture for which the package is compiled. The property lists all compatible architectures. For example, to indicate the project is compiled for x64 and x86 architectures, write the property as:

"cpu": ["x86", "x64"]

The cpu property typically appears when publishing binary packages with compiled code to indicate specific platform compatibility.

How To Manage Your package.json

To manage your package.json file, use the npm command line interface, which comes bundled with Node.js. The npm tool comes with many commands for managing package dependencies.

Note: Need to install Node.js with npm? Use one of our OS-specific installation guides:

  • Node.js and npm for CentOS
  • Node.js and npm for Debian
  • Node.js and npm for Ubuntu
  • Node.js and npm for macOS
  • Node.js and npm for Windows

The table below briefly describes common npm commands for managing apackage.jsonfile.

CommandDescription
npm initCreates a new package.json file with elementary properties. Contains prompts about the project , such as the name, version, etc.
npm installInstalls dependencies listed in the package.json file. Reads from dependencies and devDependencies properties.
npm updateChecks for newer versions and updates dependencies provided in the package.json file.
npm run <script name> Runs scripts provided in the scripts property.
npm uninstall <package>Removes a package from the dependencies or devDependencies property.

To create and update thepackage.jsonfile, use the npm commands whenever possible. The npm tools ensure the JSON file is valid and synced with the project.

When necessary, manual management is possible through a text editor.

Conclusion

After reading this guide, you're ready to manage Node.js package dependencies automatically using a package.json file. The file is essential to any Node.js project and contains important information about a package.

package.json Quick Start Guide | phoenixNAP KB (2024)

FAQs

What is package.json and what is it used for? ›

It is used by the npm CLI (and yarn) to identify your project and understand how to handle the project's dependencies. It's the package. json file that enables npm to start your project, run scripts, install dependencies, publish to the NPM registry, and many other useful tasks.

How to create a start script in package json? ›

To define an NPM script, set its name and write the script under the 'scripts' property of your package. json file: 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.

How to initialize a package json file? ›

Creating a new package. json file
  1. On the command line, navigate to the root directory of your package. cd /path/to/package.
  2. Run the following command: npm init.
  3. Answer the questions in the command line questionnaire.

How to load json faster? ›

11 Ways to Improve JSON Performance & Usage
  1. You may need multiple JSON libraries for optimal performance and features. ...
  2. Use streams whenever possible. ...
  3. Compress your JSON. ...
  4. Avoid parsing JSON if you don't need to. ...
  5. Serialize/Deserialize Larger vs Smaller JSON Objects. ...
  6. Use pre-defined typed classes.

Why would someone use json? ›

Developers often prefer JSON because it simplifies the exchange of data between different technologies. For example, when a user interacts with a web application to make a purchase, the application sends the user's input to the server in JSON format.

What is json best used for? ›

The most common uses of JSON include: It is used in writing JavaScript-based applications that have websites and browser extensions as part of their features. It is essential in the transfer of structured data across network connections. It is used to draw up data from a server by web applications.

Is package json created automatically? ›

json file is typically located in the root directory of a Node. js project and is automatically generated when you run npm init command to initialize a new project. You can also manually create and modify this file to manage your project's dependencies and configuration. For using yarn, run yarn init on your terminal.

Why is npm start used? ›

By default, the npm start command is used to start your Node. js application. However, you might need to customize this command to suit specific requirements, such as running a different entry point, adding environment variables, or incorporating additional setup steps.

How do I start json API? ›

Creating a simple JSON based API using Node. js
  1. Step 1: Install Node. ...
  2. Step 2: Initialize a blank folder, in which you would build the API. ...
  3. Step 3: Open command prompt and go to the created directory by using CD (path of the folder).
  4. Step 4: Type npm init and go through the steps, answering the asked questions.
Mar 7, 2024

Can you manually edit package json? ›

You can add dependencies to a package.json file from the command line or by manually editing the package.json file.

How to run npm start? ›

The Basics: Getting started with npm
  1. Using npm init to initialize a project.
  2. Using npm init --yes to instantly initialize a project.
  3. Install modules with npm install.
  4. Install modules and save them to your package.json as a dependency.
  5. Install modules and save them to your package.json as a developer dependency.
Feb 10, 2022

How to create package json in a folder? ›

The easiest way to create a package. json file is to run npm init to generate one for you. It will ask you to fill out some fields, and then create a package. json file in the current directory.

What is the difference between JSON and Yaml? ›

Both represent data as key-value pairs. JSON supports data objects as values, while YAML does not. However, YAML supports more data types and is closer in its use of natural language to support developer use.

What's better than JSON? ›

If you want to store several different data types with many variables, then XML is the better choice. XML checks for errors in complex data more efficiently than JSON, as XML focuses on storing data in a machine-readable way.

Why is JSON so slow? ›

Large Data Size: JSON data can be quite verbose, leading to larger file sizes when compared to binary formats. Larger data sizes can result in slower data transmission and longer loading times. Type Ambiguity: JSON is a loosely typed format, which means that it doesn't provide information about the data types.

What is the purpose of using JSON file? ›

A JSON file stores data in key-value pairs and arrays; the software it was made for then accesses the data. JSON allows developers to store various data types as human-readable code, with the keys serving as names and the values containing related data.

Why do we need package lock json? ›

The "package-lock. json" file in npm simply serves as a lockfile that captures the exact versions of packages and their dependencies. It ensures that the same versions of packages are used across different installations or environments.

What is the benefit of using json? ›

Simplicity and size

As mentioned before, one of the most significant advantages of using JSON is its small file size and, therefore, faster data transfer. Moreover, JSON's compactness with its minimal syntax and ease of reading makes it more user-friendly.

Why do we use package json in react? ›

package. json is a metadata file in a Node. js project that describes the project's dependencies, scripts, configuration, and other details. It typically contains information about the project such as its name, version, author, and license.

Top Articles
Why beginner traders fail? | Forexlive
Color experts share the 7 best shades to wear for a job interview
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Prof. Nancy Dach

Last Updated:

Views: 5904

Rating: 4.7 / 5 (57 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Prof. Nancy Dach

Birthday: 1993-08-23

Address: 569 Waelchi Ports, South Blainebury, LA 11589

Phone: +9958996486049

Job: Sales Manager

Hobby: Web surfing, Scuba diving, Mountaineering, Writing, Sailing, Dance, Blacksmithing

Introduction: My name is Prof. Nancy Dach, I am a lively, joyous, courageous, lovely, tender, charming, open person who loves writing and wants to share my knowledge and understanding with you.