One, foreword

With the development of front-end engineering and automation, modular development has become a trend of the current front-end, and package.json files are ubiquitous in a complete Node.js project. First, it occurs in the project root directory, and second, it occurs frequently in node_modules. So what does this file actually do and what does it do? Today we will reveal it to you. Micro service to repay the support of the fans the front-end, open Node. Js project, system learning Node. Js knowledge, is also in the way of you, provide systematic learning, in the process of learning any problems you can reply in the background, small make up to pull you into the group of learning together, if there is a help to raise, who remember your focus, and not miss every article on dry.

Two, learn knowledge

  • Learn what package.json can do
  • Learn how to create package.json
  • Understand the relationship between package.json and your project
  • Identify important fields and metadata
  • Know how to manage package.json
  • Understand the difference between package.json and package-lock.json

Package. json file

When we create a Node.js project, we will encounter a package.json file. It is a JSON file located at the root of the project.

Package. json contains important information about the project. It contains human-readable metadata about the project (such as the project name and description) and functional metadata (such as the package version number and list of dependencies required by the program). To understand package.json thoroughly, we have to start with the modules of Node.js. A module can be a library or a framework, or it can be a Node.js project. Node.js projects follow the modular architecture. When we create a Node.js project, the description files of these modules are called package.json files. Package. json is a very important configuration file in Node.js project, which is the core of a project. This file tracks dependencies and metadata, defines various modules required by the current project, and the configuration information of the project. It defines the various dependencies and project configuration information needed to run the project (such as project name, project version, project execution entry files, scripts executed, dependent plug-ins, project contributors, licenses, and information needed to run, develop, and selectively publish the project to NPM). . It is central to configuring and describing how to interact with and run your program, and NPM and YARN use it to identify your project and understand how to handle project dependencies. 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. A package.json file is a JSON object, and each member of that object is a setting for the current project.

Package. json plays several roles throughout the project lifecycle, some of which are only applicable to packages published to NPM, and can start your project, run scripts, install dependencies, publish to the NPM registry, and many other useful tasks. 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 was one of the main reasons it was needed in the project.

The NPM install command downloads all dependent modules from this file. Package. json is usually in the root directory of the project.

Create package.json file

There are two ways to create package.json files: manual creation and automatic creation.

4.1 Manual Creation

Create a project directory

$mkdir node-demo>cd node-demo>touch package.json
Copy the code

Directly create a package.json file in the project root directory and enter the relevant content.

{
  "name": "express-admin"."version": "1.0.0"."description": "Express Admin"."keywords": [
    "server"."express"."compression"]."homepage":"https://gitee.com/xunzhaotech/express-admin.git"."bugs":"https://github.com/owner/project/issues"."license": "MIT"."author": {
    "name": "Amber luyb"."email": "[email protected]"."url": "https://www.xunzhaotech.com"
  },
  "contributors": [{"name": "Amber luyb"."email": "[email protected]"."url": "https://gitee.com/xunzhaotech/express-admin.git"}]."funding": [{"type" : "individual"."url" : "http://example.com/donate"
    },
    "http://example.com/donateAlso",
    {
      "type" : "patreon"."url" : "https://www.patreon.com/my-account"}]."files": [".git"."CVS".".svn".".hg".".lock-wscript".".wafpickle-N".".*.swp".".DS_Store".". _ *"."npm-debug.log".".npmrc"."node_modules"."config.gypi"."*.orig,"]."main": "index.js"."browser":""."bin": {
    "myapp": "./cli.js"
  },
  "man": [
    "./man/foo.1"."./man/bar.1"]."repository": {
    "type": "git"."url": "https://gitee.com/xunzhaotech/express-admin.git"
  },
  "scripts": {
    "docs:dev": "vuepress dev docs"."docs:build": "vuepress build docs"."server": "node server.js"."start": "node index.js"."dev": "nodemon"."lint": "eslint **/*.js"
  },
  "config": {
    "port": "8080"
  },
  "devDependencies": {
    "eslint": "^ 7.22.0"."mockjs": "^ 1.1.0." "."nodemon": "^ 2.0.7." "."vuepress": "^ 1.8.2"
  },
  "dependencies": {
    "body-parser": "^ 1.19.0"."compression": "^ 1.7.4." "."cookie-parser": "^ 1.4.5." "."debug": "^ 4.3.1." "."express": "^ 4.17.1"."express-session": "^ 1.17.1"
  },
  "peerDependencies": {
    "tea": "2.x"
  },
  "peerDependenciesMeta": {
    "soy-milk": {
      "optional": true}},"bundledDependencies": [
    "renderized"."super-streams"]."optionalDependencies": {},"engines": {
    "npm": "~ 1.0.20"
  },
  "os": [
    "darwin"."linux"]."cpu": [
    ! "" arm".! "" mips"]."private": false."publishConfig": {},"workspaces": [
    "./packages/*"]}Copy the code

4.2 Automatic Creation

After creating a yarn init -y or NPM init -y command in the root directory of the project, you can also enter NPM init or yarn init -y to ask the user to answer some questions in an interactive manner. Then follow the prompts to enter the corresponding content step by step. After completion, a basic package.json file will be added to the project directory. Of all the questions, only the project name and project version are mandatory, the others are optional. As follows:

{
 "name": "my-test".# Project name
  "version": "1.0.0".# Project version (format: large version. Minor version. Minor version)
  "author": "".# the author
  "description": "".# Project Description
  "main": "index.js".# import file
  "scripts": {        # Specify the NPM command line abbreviation to run the script command
      "test": "echo \"Error: no test specified\" && exit 1"
  },
"keywords": [].# keywords
"license": "ISC"      # the license
}
Copy the code

5. Package. json file configuration description

We know that some of the most common and important fields contained in package.json are used to manage project configuration information or 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.

5.1 Required Fields

There are many configuration items in package.json, and the two fields that must be filled in are the name field and the Version field, which are unique identifiers that make up an NPM module.

name

The name field defines the name of the module, which should be named according to some official specifications and recommendations:

  • The project/module name must contain no more than 214 characters and cannot start with a period (.) or an underscore (_). It cannot contain uppercase letters.
  • The module name becomes the module URL, a parameter on the command line, or a folder name, and any non-URL-safe characters cannot be used in the module name (validate-npm-package-name can be used to check for valid module names).
  • Semantic module names can help developers find needed modules more quickly, and avoid accidental acquisition of wrong modules;
  • If there are some symbols in the module name, remove the symbols to ensure that they are not the same as the existing module name.

The name field must be unique from other module names. You can run the following command to check whether the module name is used: NPM view Alternatively, you can enter the module name in NPM. If the module name cannot be found, you can use the module name.

version

  • In package.json files, version is a very important concept. Module versions in NPM packages are required to follow the SemVer specification. The standard version number of the specification is in the format of X.Y.Z, where X, Y, and Z are non-negative integers and zero padding before numbers is prohibited:
  • X is the major number: the first digit is the major number. In general, major feature updates or feature additions that are not backward compatible will raise the version number.
  • Y is the minor version number: the middle digit refers to the minor version number. In general, the addition of some functionality that is backward compatible will increase the version number.
  • Z is patch number: the last digit is the patch version number. In general, this version number will be increased if there are some BUG fixes on the project.

When a release is large, unstable, and may not meet the expected compatibility requirements, we may want to release an advanced release first.

The prior version number can be added to the major version number. The revision number is followed by a sequence of period-separated identifiers and version compilation information with a – sign:

  • Internal Version (Alpha)
  • Public Beta (Beta)
  • Release candidate RC (Release candiate)

We can run the following command to view the version of the module:

$npm view <packageName> version  View the latest version of a module
$npm view <packageName> versions View all historical versions of a module
Copy the code

5.2 Optional Fields

Optional fields are the item information that needs to be added to remove the required fields

Description & Keywords

  • Description: The field is a string of characters used to add the description of the module. It helps people find this package when using NPM Search.
  • Keywords project keywords, which are an array of strings. Used to add keywords to modules. It helps people find this package when using NPM Search.
  • When we use NPM to retrieve the module, the description field and keywords field in the module will be matched. Writing description and keywords in package.json will help increase the exposure of our module.

Install project Dependencies (Dependencies & devDependencies)

  • Dependencies: Field specifies the module on which the project runs (in production).
  • DevDependencies: Specifies the modules that the project needs to develop (in the development environment, the project needs to rely on).

    We are using the VUE framework to develop a program, the development stage needs to use Webpack to build your development and local running environment. Make sure to include vUE in Dependencies, because the program will be used in production. Webpack is a tool that you use to compress your code, pack it, and put it in devDependencies. Or if you’re writing a program that uses the ES6 standard, and the browser doesn’t support it completely, you need to use Babel to convert the code. Babel puts devDependencies. If you want to use antD, add dependencies to antD.

Simplified Terminal Commands (scripts)

The scripts field is a metadata feature in package.json that accepts an object with the property of a script that can be run through NPM run and the value of the actual run command (usually terminal command), such as:

  "scripts": {
     "dev": "nuxt"."build": "nuxt build"."start": "nuxt start"."generate": "nuxt generate"
 },
Copy the code

Putting terminal commands into the scripts field allows you to both record them and reuse them easily.

Define project entry (Main)

The main field is another metadata feature in package.json that can be used to specify the entry file to load. If your project is an NPM package, when the user installs your package, const ModuleName = require(‘module-name’) returns the module.exports property of the file listed in the main field. When the main field is not specified, the default is the index.js file under the module root.

Publish file Configuration (Files)

The files field describes the list of files that we push to the NPM server after using the NPM publish command. If you specify a folder, the contents of the folder will be included. We can view the downloaded antD package.json files field as follows:

"Files ": ["dist", "lib", "es"... .Copy the code

The antD package contains /dist/”lib/es files in the following directory structure. In addition, we can also configure a.npmignore file to exclude some files and prevent a large number of junk files pushed to NPM.

Define a private module (private)

For corporate non-open source projects, the private property is set to true because NPM refuses to distribute private modules. This prevents private modules from being unintentionally distributed.

Operating system (OS) for specified module

You can use OS properties to specify the system for which the module is applicable, or to specify a blacklist of systems that cannot be installed (an error occurs when installing a module on a system in the blacklist).

"OS" : [" Darwin ", "Linux"] # applicable system "OS" : [! "win32"] # blacklistCopy the code

In the Node environment, you can use process.platform to determine the operating system

Specify module for CPU architecture (CPU)

We can use the CPU field to more precisely limit the user’s installation environment

"CPU" : [" x64 ", "ia32"] # for CPU "CPU" : [! "arm", "! MIPS "] # blacklistCopy the code

In the Node environment, you can use process.arch to determine the CPU architecture

Specify the Project Node version (Engines)

Prevent node versions from causing many strange problems (such as some dependency installation errors, dependency installation projects will not run, etc.).

"Engines" : {" node ":" > = 8.16.0 ", "NPM" : "> = 6.9.0"},Copy the code

Note that the Engines attribute serves only as an illustration and does not affect the installation of dependencies if the user version does not match the specified value

Custom Command (bin)

The bin field is used to specify the location of the executable file corresponding to each internal command. When package.json provides the bin field, it is equivalent to making a mapping between the command name and the local file name. When a user installs a package with the bin field,

  • For a global installation, NPM will use symbolic links to link these files to /usr/local/node_modules/.bin/;
  • /node_modules/.bin/ will be linked to if installed locally.

If you want to use mfD-cli as the command, you can configure the following bin field:

"bin": {
  "mfd-cli": "./bin/cli.js"
  }
Copy the code

The above code specifies that the executable file corresponding to the mfd-cli command is cli.js in the bin subdirectory, so it is easy to use NPM to execute scripts in projects where the Mfd-cli package is installed:

"scripts": {
    start: 'node node_modules/.bin/mfd-cli'
 }
Copy the code

This doesn’t look quite the same as vue create/create-react-app, right? Because: Node_modules /. Bin. Otherwise, MFD -cli will look for MFD -cli.js in the current path. That can’t be right. To achieve something as simple as a command like vue create/create-react-app, you can write the following command in the first line of the cli.js executable in the bin subdirectory mentioned above: #! The /usr/bin/env node command tells the system to parse using node, so it can be shortened to MFD -cli.

Set the app root path (homepage)

The react project uses the built-in webpack configuration by default. If the package.json file does not contain a homepage property, the build-packed file resource application path is/by default.

Generally, the static resources we pack will be deployed on the CDN. In order to let our application know where to load the resources, we need to set a root path. In this case, we can set the root path of our application through the homepage field in package.json.

After we set the homepage property:

{
    "homepage": "https://xxxx.cdn/project-name",
}
Copy the code

The packaged resource path will add the address of homepage: /project-name/bundle.js

Other configuration

  • Author: project developer, whose value is your valid account name at npmjs.org, following the “account name < email >” rule, for example: [email protected].
  • Private: indicates whether it is private. When this parameter is set to true, NPM refuses to publish.
  • License: License terms that let users know their rights and limitations.
  • Bugs: The address for submitting bugs.
  • Ficol3: Project contributors.
  • Repository: project repository address.
  • The module: It is loaded in ES Module(also known as ES6 modular mode), because in the early days when there was no ES6 modular solution, it followed the CommonJS specification, and the CommonJS specification package represented the entry file in the way of main. In order to distinguish, Module mode was added. However, the ES6 modular scheme is more efficient. Therefore, the SYSTEM checks whether the Module field exists before using the main field.
  • EslintConfig: EsLint checks file configuration and automatically reads validation.
  • Browserslist: List of versions for use by browsers.
  • Style: The position of the style file when used by the browser; Style file packaging tool Parcelify, which knows where to package style files.

Package. json and package-lock.json

Package. json is a package-lock.json file. When the node_modules folder does not exist or has been deleted, NPM install is required to reload all dependencies. Using package-lock.json, you can directly indicate the download address and dependencies, which is faster and less prone to errors.