Translation: Crazy geek

Original text: heynode.com/tutorial/wh…

Reproduced without permission

The Node project tracks dependencies and metadata in a file called package.json in the project root directory. This is the core of your project. It contains information such as name, description, and version, as well as information needed to run, develop, and selectively publish projects to NPM.

In this tutorial, we will:

  • To understandpackage.jsonRelationships with projects
  • Identify important fields and metadata
  • Know how to managepackage.json

The target

Learn what a package.json file is, how it relates to your project, and common properties to know.

To understandpackage.json

If you’ve used Node.js before, you may have come across package.json files. It is a JSON file located in the root directory of the project. Your package.json contains important information about your project. It contains human-readable metadata about the project (such as the project name and description) and functional metadata (such as package version numbers and a list of dependencies required by the program).

An example of package.json looks like this:

 {
        "name": "my-project"."version": "1.5.0"."description": "Express server project using compression"."main": "src/index.js"."scripts": {
            "start": "node index.js"."dev": "nodemon"."lint": "eslint **/*.js"
        },
        "dependencies": {
            "express": "^ 4.16.4"."compression": "~ 1.7.4." "
        },
        "devDependencies": {
			"eslint": "^ 5.16.0"."nodemon": "^ 1.18.11"
        },
		"repository": {
			"type": "git"."url": "https://github.com/osiolabs/example.git"
		},
		"author": "Jon Church"."contributors": [{
			"name": "Amber Matz"."email": "[email protected]"."url": "https://www.osiolabs.com/#team"}]."keywords": ["server"."osiolabs"."express"."compression"]}Copy the code

package.jsonWhat is the use of?

The project’s package.json is central to configuring and describing how the program interacts with and runs. NPM CLI (and YARN) uses it to identify your project and learn how to handle project dependencies. Package. json files enable NPM to launch your projects, run scripts, install dependencies, publish to the NPM registry, and many other useful tasks. The NPM CLI is also the best way to manage package.json, as it helps generate and update package.json files throughout the life of the project.

Package. json plays multiple roles in the life cycle of a project, some of which only apply to packages published to NPM. Even if you don’t publish your project to the NPM registry or publicly publish it to others, package.json is still vital to the development process.

Your project must also include package.json before you can install packages from NPM. This is probably one of the main reasons you need it in your project.

package.jsonCommon fields in

Let’s take a look at some of the most common and important fields included in package.json to better understand how to use and manage this basic file. Some are used to publish to NPM, while others help the NPM CLI run applications or install dependencies.

There are more actual fields than we’ve covered, and you can learn about the rest in its documentation, but here are the package.json properties you must know about.

name

"name": "my-project"
Copy the code

The name field defines the name of the package. This is the name the package will display in the NPM registry when published. It can be no longer than 214 characters, can only be lowercase, and must be URL-safe (hyphens and underscores are allowed, but Spaces or other characters are not allowed in urls).

If you are publishing a package to NPM, the name attribute is required and must be unique. If you try to publish a package with a name that is already in use on the NPM registry, you receive an error message. Name does not have to be unique if your package is not intended to be distributed to NPM.

version

"Version" : "1.5.0."Copy the code

The Version field is important for any released software package and is required prior to release. This is the current version of the software described by package.json.

You don’t need to use SemVer, but it is the standard used in the Node.js ecosystem and is highly recommended. This property is not strictly required for unpublished packages. Usually the version number is increased according to SemVer before a new version is released to NPM. This workflow is typically not used when packages are not relied on as dependencies or are not published to NPM. But if you are using a package as a dependency, it is important to make sure that the Version field is up to date to ensure that others are using the correct version of the package. Learn more about Semantic versioning.

license

This is a very important but often overlooked attribute. The license field allows us to define a license that applies to the code described in package.json. Again, this is important when publishing a project to the NPM registry, because the license may restrict the use of the software by some developers or organizations. Having a clear license helps to clearly define the terms that the software can use.

The value of the license field is usually the license identifier code — for example, a string like MIT or ISC that stands for MIT and ISC licenses. If you don’t want to provide a license, or if you explicitly don’t want to grant permission to use a private or undistributed package, you can use UNLICENSED as a license. Choose a License is a useful resource if you are unsure which License to use.

authorcontributors

"author": "Jon Church [email protected] https://www.osioslabs.com/#team",
"contributors": [{
	"name": "Amber Matz",
	"email": "[email protected]",
	"url": "https://www.osiolabs.com/#team"
}],
Copy the code

The Author and Polymorphism fields function similarly. They’re all people fields, and they can be strings in the form of “Name”, or they can be objects with Name, email, URL fields. Both email and URL are optional.

Authors are only available for one person, and those can consist of multiple individuals.

These fields are a useful way to list contacts for public projects and to share credits with contributors.

description

The NPM registry uses the Description field for published packages to describe them in search results and on nPMjs.com.

This string is used to help understand packages when the user searches the NPM registry. This should be a short summary of the package.

Even if you don’t publish it to the NPM registry, it can be used as a simple document for your project.

keywords

"keywords": ["server", "osiolabs", "express", "compression"]
Copy the code

The keywords field is an array of strings and acts like a description. The NPM registry indexes these fields to help find them when someone searches for packages. Each value in the array is a key associated with your package.

If you do not publish to the NPM registry, this field is of little use and can be ignored.

main

"main": "src/index.js",
Copy the code

The main field is a functional property of package.json. It defines the entry point for the project, usually the file used to launch the project.

If your package (for example, named foo-lib) was installed by the user, then when the user executes require(‘foo-lib’), this is the module.exports property of the file listed in the main field returned by require.

Its value is usually the index.js file in the project root, but it can also be any file you choose as the main entry to the package.

scripts

"scripts": {
	"start": "node index.js",
	"dev": "nodemon"
}
Copy the code

The scripts field is another metadata feature in package.json. The scripts property accepts an object whose value is the script that can be run through NPM run and whose key is the command that was actually run. These are usually terminal commands, and we put them in the scripts field so that we can both record them and easily reuse them.

Scripts is a powerful tool used by the NPM CLI to run project tasks. They can perform most of the tasks in the development process. Learn more about NPM scripts.

repository

"repository": {
	"type": "git",
	"url": "https://github.com/osiolabs/example.git"
}
Copy the code

You can record the repository in which the project code resides by providing the repository field. This field is an object that defines the URL where the source code resides and the type of version control system it uses. For open source projects, it might be GitHub or Bitbucket with Git as the version control system.

It is important to note that the URL field is intended to point to a location from which version control can be accessed, not just to the published code base.

dependencies

"Dependencies" : {" express ", "^ 4.16.4", "compression will" : "~ 1.7.4}"Copy the code

This is one of the most important fields in package.json, listing all the dependencies used by the project (the external code that the project depends on). When you install a package using NPM CLI, it will download to your node_modules/ folder and add an entry to your dependency properties, noting the name of the package and the installed version.

The Dependencies field is an object in which the package name is the key and the version or version range is the value. From this list, NPM knows which packages (and versions) to get and install when it runs NPM Install in a directory. The Dependencies field of package.json is at the heart of the project and defines the external packages required by the project.

The caret (^) and tilde (~) seen in dependent versions are representations of the version range defined in SemVer. Learn more about dependent versions and SemVer.

devDependencies

"DevDependencies ": {"nodemon": "^1.18.11"}Copy the code

Similar to the Dependencies field, but the packages listed here are only needed during development, not in production.

For example, using a tool to reload a project during development, such as Nodemon, will not be used once the program is deployed and put into production. The devDependencies property allows us to specify which dependencies are not needed in production. When installing applications in a production environment, you can use NPM Install — Production to install only what is listed in the Package. json dependency field.

DevDependency is a good way to document what tools your program needs during development. To install NPM’s package as devDependency, run NPM install –save-dev.

Another use of the devDependencies attributes is to use them in our NPM script. Learn more about using devDependencies in NPM scripts.

Manage yourpackage.json

The package.json file must be valid JSON. This means that any missing commas, missing quotes, or other formatting errors will prevent NPM from interacting with package.json. If you do introduce an error, you will see it the next time you run the NPM command. It is recommended to use the NPM CLI to update and manage package.json whenever possible to avoid accidentally introducing errors into package.json.

Creating your package.json using NPM init will help ensure that you generate valid files.

It is best to manage dependencies using the NPM commands NPM install, NPM uninstall, and NPM update to keep your package.json and node_modules/ folders in sync. To add the dependency list manually, you need to run NPM Install before actually installing the dependencies into the project.

Because package.json is just where we record our dependencies, and the node_modules/ folder is where the dependency code is actually installed, manually updating the package.json dependency fields will not immediately reflect our status to the node_modules/ folder. This is why NPM is used to help manage dependencies, as it updates both package.json and node_modules/ folders.

You can of course manually edit package.json and make changes in a text editor, as long as you are careful not to introduce any JSON formatting errors, and this works for most fields. But I recommend using the NPM CLI command whenever possible.

conclusion

The package.json file is the heart of the Node project. It records important metadata about the project required before it is published to NPM, and it defines the project functionality attributes that NPM uses to install dependencies, run scripts, and identify entry points for packages.

Not all fields in package.json will apply to you, but you can get some powerful benefits by recording information about your program in package.json files. Understanding the role of package.json and its relationship to NPM is an important part of developing Node.js applications and is increasingly becoming an important part of the JavaScript ecosystem.

Learn more

  • What other formats can you provide repositories in? (docs.npmjs.com)
  • How do I add private fields to your package.json to affect publishing to NPM? (docs.npmjs.com)

Other resources

  • Npm-package. json: Details of package.json handling for NPM (docs.npmjs.com)
  • Choose an open Source license (choosealicense.com)

Welcome to pay attention to the front end public number: front end pioneer, receive webpack full series of tutorials.