This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.


Today, let’s take a look at some of the configurations associated with the package.json file on the front end. Knowing these configurations will help us improve our development efficiency and standardize our projects. The article content is more, the suggestion collects in the study first!

In every front-end project, there is a package.json file, which is a configuration file for the project. Common configurations include configuring project startup, packaging commands, and declaring dependency packages. The package.json file is a JSON object, each member of which is a setting for the current project. As package.json serves as a front-end steward, what configuration is relevant to our daily development? Let’s take a closer look at this file.

When we build a new project, scaffolding usually initializes a package.jaon configuration file in the root directory of the project. When initializing a project using the react scaffolding (create-react-app), the package.json file reads as follows:

{
  "name": "my-app"."version": "0.1.0 from"."private": true."dependencies": {
    "@testing-library/jest-dom": "^ 5.14.1." "."@testing-library/react": "^ 11.2.7"."@testing-library/user-event": "^ 12.8.3"."react": "^ 17.0.2"."react-dom": "^ 17.0.2"."react-scripts": "4.0.3"."web-vitals": "^ 1.1.2." "
  },
  "scripts": {
    "start": "react-scripts start"."build": "react-scripts build"."test": "react-scripts test"."eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app"."react-app/jest"]},"browserslist": {
    "production": [
      "0.2%" >."not dead"."not op_mini all"]."development": [
      "last 1 chrome version"."last 1 firefox version"."last 1 safari version"]}}Copy the code

When we clone a new project to the local, we need to run the NPM install (yarn install) command to install the dependency files required by the project. When this command is executed, the required modules are automatically downloaded based on the configuration information in the package.json file, which is the runtime and development environment required to configure the project.

Common configuration items of package.json are:

One, must attribute

The two most important fields in package.json are name and version, both of which are required; without them, the NPM install command cannot be executed properly. NPM specifies that package.json files are uniquely identified by name and version number.

1. name

Name is easy to understand. It is the name of the project, and it is a string. When naming the name field, note the following:

  • The name must contain no more than 214 characters and cannot start with “. And “_”, cannot contain uppercase letters (this is because when packages are distributed on NPM, they get their own urls based on this property, so cannot contain non-URL-safe characters);
  • The name can be passed into require(“”) as an argument to import modules, so it should be as short and semantic as possible;
  • The NPM view command can be used to check whether the module name is the same as that of other modules. If the module name is the same, 404 will be displayed:

If there is a corresponding package on the NPM package, the package details are displayed:In fact, many of the projects we work on are not published on NPM, so whether the name is standard or not may not matter so much that it will not affect the project. If you want to publish on NPM, the name field must meet the requirements.

2. version

The Version field represents the version number of the project package, which is a string. After each project change, the project version number should be changed synchronously at the time of release. The specifications for using version numbers are as follows:

  • The version number is named according to the semantic version 2.0.0 specification in the format: major version number. Revision number: Usually, modifying the major version number is to make large functional changes, modifying the minor version number is to add new features, modifying the revision number is to fix some bugs;
  • If the changes to a version are large and unstable, and it is possible to meet the expected compatibility requirements, the prior version needs to be released. The prior version is followed by a dot-separated identifier with a “-” to connect to the build information: Internal (alpha), public beta (beta), and release candidate (RC, release Candiate).

You can run the following command to view the version of the NPM package. The React package is used as an example:

// Check the latest version
npm view react version
// View all versions
npm view react versions
Copy the code

When the second command is executed, the result is as follows:

2. Description

There are five configuration fields in package.jaon that relate to the project package description information, and here’s what they mean.

1. description

The Description field is used to describe the package, which is a string that allows other developers to find our package in NPM searches.

2. keywords

The keywords field is an array of strings representing the keywords of the project package. As with Description, it is used to increase the exposure of the project package. Here are the descriptions and keywords of the ESLint package:

3. author

Author, as the name implies, is the author of the project package. It has two forms, one is a string format:

"author": "CUGGZ <[email protected]> (https://juejin.cn/user/3544481220801815)"
Copy the code

The other is object form:

"author": {
  "name" : "CUGGZ"."email" : "[email protected]"."url" : "https://juejin.cn/user/3544481220801815"
}
Copy the code

4. contributors

Unlike the author, that field is an array containing all the contributors. It can also be written in two ways:

"contributors": [
  "CUGGZ0 <[email protected]> (https://juejin.cn/user/3544481220801815)"."CUGGZ1 <[email protected]> (https://juejin.cn/user/3544481220801815)"
 ]
Copy the code
"contributors": [{"name" : "CUGGZ0"."email" : "[email protected]"."url" : "https://juejin.cn/user/3544481220801815"
	},
  {
  	"name" : "CUGGZ1"."email" : "[email protected]"."url" : "https://juejin.cn/user/3544481220801815"}]Copy the code

5. homepage

A homepage is the homepage of the project. It is a string.

6. repository

A repository represents the location in which code is stored. It is usually written in one of two ways. The first is a string:

"repository": "https://github.com/facebook/react.git"
Copy the code

In addition, you can set the version control system explicitly, which is in the form of an object:

"repository": {
  "type": "git"."url": "https://github.com/facebook/react.git"
}
Copy the code

7. bugs

Bugs represents the address where the project submitted the problem. This field is an object that can add the address of the submitted problem and the email address for feedback:

"bugs": { 
  "url" : "https://github.com/facebook/react/issues"."email" : "[email protected]"
}
Copy the code

The most common bugs are the Issues page on Github. Here is the address of the Issues page on React.

Dependency configuration

Typically, our project will rely on one or more external dependencies, which can be configured under the following five properties, depending on their purpose: Dependencies, devDependencies, peerDependencies, bundledDependencies, optionalDependencies. Here’s a look at what each property means.

1. dependencies

The Dependencies field declares the dependency packages that are required in the project’s production environment. When the NPM package is installed using NPM or YARN, the NPM package is automatically inserted into this configuration item:

npm install <PACKAGENAME>
yarn add <PACKAGENAME>
Copy the code

When using the –save parameter when installing dependencies, the newly installed NPM package is also written to the Dependencies property.

npm install --save <PACKAGENAME>
Copy the code

The value of this field is an object whose members, consisting of the module name and corresponding version requirements, represent the dependent module and its version range.

"dependencies": {
   "react": "^ 17.0.2"."react-dom": "^ 17.0.2"."react-scripts": "4.0.3",},Copy the code

Each configuration item is a key-value pair. Key indicates the module name and value indicates the module version. Version number follows the major version number. The format of the revision number is as follows:

  • Fixed version: The react-Scripts version 4.0.3 is fixed, and only the specified version is installed.
  • Tilde: for example, ~4.0.3 indicates that the latest version of 4.0.x is installed (not less than 4.0.3), that is, the major version and this version will not be changed during installation.
  • Insert number: for example, the react version ^17.0.2 above indicates that the latest version of 17.x.x will be installed (at least 17.0.2), which means that the main version will not be changed during installation. If the main version number is 0, the insertion and tilde behave the same;
  • Latest: Installs the latest version.

Be careful not to include tests or transitional dependencies in dependencies to avoid unexpected problems in the production environment.

2. devDependencies

DevDependencies declares dependencies that are needed during development, such as Webpack, Eslint, Babel, etc., to aid development. They differ from Dependencies in that they only need to be installed on the development device and do not need to run the code in production. These packages are not needed when the package goes live, so you can add these dependencies to devDependencies, which are still installed and managed when NPM install is specified locally, but not in production.

If NPM or YARN is used to install the software package, the newly installed NPM package is automatically added to the list if the following parameters are specified:

npm install --save-dev <PACKAGENAME>
yarn add --dev <PACKAGENAME>
Copy the code
"devDependencies": {
  "autoprefixer": "^ 7.1.2." "."babel-core": "^ 6.22.1"
}
Copy the code

3. peerDependencies

In some cases, both our project and the module on which we depend depend on another module, but in different versions. For example, our project relies on version 1.0 of module A and module B, and module A itself relies on version 2.0 of module B. In most cases, this is not a problem and both versions of the B module can coexist and run at the same time. There is a situation, however, where the problem is that this dependency is exposed to the user.

The most typical scenario is A plug-in, such as module A being A plug-in for module B. The user installed module B is version 1.0, but plug-in A can only be used with module B of version 2.0. At this point, users will have problems if they pass an instance of version 1.0 B to A. Therefore, A mechanism is needed to remind the user when the template is installed that if A and B are installed together, then B must be A 2.0 module.

The peerDependencies field is used by the plug-in to specify the version of the main tool that it needs.

"name": "chai-as-promised"."peerDependencies": {
   "chai": "1.x"
}
Copy the code

The code above specifies that when installing the Chai-as-Promised module, the main program CHAI must be installed together, and the version of CHAI must be 1.x. If the dependency specified by the project is chai version 2.0, an error is reported.

Note that starting with NPM 3.0, peerDependencies are no longer installed by default.

4. optionalDependencies

If you want NPM to continue running when the package is not found or the installation fails, you can place the package in the optionalDependencies object, which overwrites the package of the same name in the Dependencies object. So you only need to set it up in one place.

Note that the dependencies in optionalDependencies may not have been installed successfully, so you must do exception handling otherwise an error will be reported if you do not get the dependency.

5. bundledDependencies

The bundledDependencies configuration item is an object. The bundledDependencies configuration item is an array that specifies modules that are packaged together when the package is published.

Note that the values in this array must be the packages declared in Dependencies and devDependencies.

6. engines

When maintaining older projects, there may be special requirements for the version of the NPM package or Node version that will not get the project running. To get your project out of the box, specify the specific version number in the Engines field:

"engines": {
	"node": "> = 8.10.3 < 12.13.0"."npm": "> = 6.9.0"
}
Copy the code

Note that Engines serves only as an illustration and does not affect the installation of dependent packages even if the user installs an incorrect version.

4. Script configuration

1. scripts

Scripts is a built-in script entry in package.json. It is key-value configuration. Key is a runnable command that can be executed through NPM run. In addition to running the basic scripts command, you can also combine pre and POST for pre and subsequent operations. Let’s start with a set of scripts:

"scripts": {
	"dev": "node index.js"."predev": "node beforeIndex.js"."postdev": "node afterIndex.js"
}
Copy the code

All three js files have a console:

// index.js
console.log("scripts: index.js")
// beforeIndex.js
console.log("scripts: before index.js")
// afterIndex.js
console.log("scripts: after index.js")
Copy the code

When we execute the NPM run dev command, the output is as follows:

scripts: before index.js
scripts: index.js
scripts: after index.js
Copy the code

As you can see, all three commands are executed in the order predev→dev→postdev. If the scripts commands have a certain sequence, you can use the three configuration items to run the commands separately.

By configuring the scripts property, you can define some common operation commands:

"scripts": {
  "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js"."start": "npm run dev"."unit": "jest --config test/unit/jest.conf.js --coverage"."test": "npm run unit"."lint": "eslint --ext .js,.vue src test/unit"."build": "node build/build.js"
}
Copy the code

These scripts are command-line applications. They can be run by calling NPM run XXX or YARN XXX, where XXX is the name of the command. For example, NPM run dev. We can use any name for the command, and the script can be any operation.

Good use of this field can greatly improve development efficiency.

2. config

The config field is used to configure the configuration parameters for the scripts runtime, as shown below:

"config": {
	"port": 3000
}
Copy the code

If you run NPM run start, the port field is mapped to the nPM_package_config_PORT environment variable:

console.log(process.env.npm_package_config_port) / / 3000
Copy the code

Users can override the value of port by using the NPM config set foo:port 3001 command.

5. Files & Directories

Let’s take a look at the package.json properties associated with files and directories.

1. main

The main field specifies the entry file to load, which is available in both browser and Node environments. If we published the project as an NPM package, then importing the NPM package using require would return the module.exports property of the file listed in the main field. If this field is not specified, the default is index.js in the project root directory. If not found, an error is reported.

The value of this field is a string:

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

2. browser

The Browser field defines entry files for NPM packages in the Browser environment. If the NPM package is only used on the Web side and is strictly prohibited on the server side, use Browser to define the entry file.

"browser": "./src/index.js" 
Copy the code

3. module

The Module field defines the entry file for the ESM specification of the NPM package, which can be used by both browser and Node environments. If the NPM package exports an ESM specification package, use module to define the entry file.

"module": "./src/index.mjs".Copy the code

Note that.js files use commonJS specification syntax (require(‘ XXX ‘)) and.mjs uses ESM specification syntax (import ‘XXX ‘).

The configuration of the above three entry files is different, especially in different usage scenarios. In the Web environment, if loader is used to load ESM (ES Module), the loading sequence of these three configurations is browser→module→main. If require is used to load CommonJS modules, the loading sequence is main→module→browser.

Webpack has a target option when building a project, which defaults to Web, that is, build a Web application. If you need to compile some homogeneous projects, such as a Node project, you simply set the webpack.config.js target option to Node to build. If you load CommonJS modules or ESM in a Node environment, only the main field is valid.

4. bin

The bin field is used to specify the location of the executable file for each internal command:

"bin": {
  "someTool": "./bin/someTool.js"
}
Copy the code

Node_modules /.bin/someTool; node_modules/.bin/someTool; Since the node_modules/.bin/ directory adds the system’s PATH variable at run time, these scripts can be invoked directly with commands without paths when running NPM. Therefore, the following can be abbreviated:

scripts: {  
  start: './node_modules/bin/someTool.js build'
}

/ / short
scripts: {  
  start: 'someTool build'
}
Copy the code

All commands in node_modules/. Bin/can be run in the NPM run [command] format.

The above configuration provides a bin field mapped to the local filename in package.json package China, which the NPM package will then link to in prefix/fix for global import. Or link to a local node_modules/.bin/ file for use in this project.

5. files

The Files configuration is an array describing the list of files that need to be specified when installing the NPM package as a dependency. When the NPM package is published, the file specified as files will be pushed to the NPM server. If the folder is specified, all files under that folder will be committed.

"files": [
    "LICENSE"."Readme.md"."index.js"."lib/"
 ]
Copy the code

If there are files that you do not want to commit, you can create a. Npmignore file in the root directory of the project and specify the files that do not need to be committed to prevent junk files from being pushed to NPM. This file has a similar form to.gitignore. Files written to this file are excluded even if they are written to the files property. For example, you could write this in the file:

node_modules
.vscode

build

.DS_Store
Copy the code

6. man

The man command is a help command in Linux. You can use this command to view the help information in Linux, such as the command help, configuration file help, and programming help. If the Node.js module is a global command line tool, you can specify the address of the document searched by the man command in package.json via the man property:

"man": [
	"./man/npm-access.1"."./man/npm-audit.1"
]
Copy the code

The MAN field can specify one or more files, and the contents of the document are presented to the user when man {package name} is executed.

Note:

  • The man file must end with a number and, if compressed, can use the. Gz suffix. This number indicates which MAN section the file is installed in;
  • If the man file name does not start with the module name, the installation will be prefixed with the module name.

For the above configuration, you can use the following command to view the document:

man npm-access
man npm-audit
Copy the code

7. directories

The directories field is used to specify the directory for the project. Node.js modules are implemented based on the CommonJS modular specification, which must be strictly followed. In addition to the package project description file package.json, the module directory must contain the following directories:

  • Bin: directory for storing executable binary files
  • Lib: the directory for storing JS code
  • Doc: directory for storing documents
  • Test: Directory for storing unit test case code
  • .

In the actual project directories, we might not be named according to this specification, so specify the file path for each directory in the directories field:

"directories": {
    "bin": "./bin"."lib": "./lib"."doc": "./doc"."test" "./test"."man": "./man"
},
Copy the code

This attribute actually has no practical use, and certainly does not rule out meaningful use in the future.

Publish configuration

Let’s take a look at the configuration associated with NPM project package publishing.

1. private

The private field prevents us from accidentally publishing private libraries to the NPM server. Just set this field to true:

"private": true
Copy the code

2. preferGlobal

The preferGlobal field indicates that a warning is displayed if set to true when the user does not install this module as a global module. It doesn’t really prevent the user from doing a partial installation, it just alerts the user to avoid misunderstanding:

"preferGlobal": true
Copy the code

3. publishConfig

The publishConfig configuration takes effect when a module is published and is used to set a collection of configuration items for publication. You can configure the tag or repository address here if you do not want the module to be marked as up to date by default or published to a public repository. For more detailed configuration, see npm-config.

Normally, publishConfig is used in conjunction with private. If you only want the module to be published to a particular NPM repository, you can configure it like this:

"private": true."publishConfig": {
  "tag": "1.1.0"."registry": "https://registry.npmjs.org/"."access": "public"
}
Copy the code

4. os

The OS field allows us to set which operating systems the NPM package can and cannot be used on. If we want to develop an NPM package that runs only on Linux, we recommend that Windows users do not install it to avoid unnecessary exceptions. In this case, we can use OS configuration:

"os" ["linux"]   // The applicable operating system
"os" [! "" win32"]  // Disable the operating system
Copy the code

5. cpu

This configuration is similar to the OS configuration. The CPU can more accurately limit the user’s installation environment:

"cpu" ["x64"."AMD64"]   // The applicable CPU
"cpu" [! "" arm".! "" mips"]  // Disable CPU
Copy the code

As you can see, the difference between the blacklist and whitelist is that the blacklist is preceded by a “! “. .

6. license

The license field specifies the open source license of the software. The open source license describes the rights that others have after obtaining the code, which operations can be performed on the code, and which operations are prohibited. Common protocols are as follows:

  • MIT: As long as the user includes the copyright notice and license notice in the project copy, they can do whatever they want with your code without any liability on your part.
  • Apache: Similar to MIT, but also contains provisions for contributors to license patents to users.
  • GPL: When a user who has modified the project code redistributes the source code or binary code, he must publish his changes.

The field can be declared like this:

"license": "MIT"
Copy the code

7. Third-party configuration

Package. json files can also carry command-specific configurations, such as Babel, ESLint, and so on. They each have unique properties, such as eslintConfig, Babel, and so on. They are command-specific and can be found in the corresponding command/project documentation for how to use them. Let’s look at some common third-party configuration items.

1. typings

The Typings field is used to specify TypeScript entry files:

"typings": "types/index.d.ts".Copy the code

This field has the same effect as the main configuration.

2. eslintConfig

The configuration of ESLint can be written in a separate configuration file. Eslintrc.json, or in the eslintConfig configuration item in package.json.

"eslintConfig": {
      "root": true."env": {
        "node": true
      },
      "extends": [
        "plugin:vue/essential"."eslint:recommended"]."rules": {},
      "parserOptions": {
        "parser": "babel-eslint"}},Copy the code

3. babel

Babel is used to specify the compilation configuration of Babel as follows:

"babel": {
	"presets": ["@babel/preset-env"]."plugins": [...]. }Copy the code

4. unpkg

Use this field to enable the CDN service for all files on the NPM. The CND service is provided by UNPKG:

"unpkg": "dist/vue.js"
Copy the code

5. lint-staged

Lint-staged is a tool that runs Linters on Git staging files and configures them to perform lint checks on all files one file at a time, usually in conjunction with gitHooks.

"lint-staged": {
	"*.js": [
  	"eslint --fix"."git add"]}Copy the code

Lint-staged versions only inspect the currently modified file each time code is submitted.

6. gitHooks

GitHooks is used to define a hook that performs ESlint checks before committing. After executing the lint command, files in the staging area are automatically repaired. The repaired files are not stored in the staging area, so you need to add them back to the staging area with the git add command. After executing the pre-commit command, if there are no errors, the git commit command is executed:

"gitHooks": {
	"pre-commit": "lint-staged"
}
Copy the code

This is done in conjunction with lint-staged code inspections described above.

7. browserslist

The browserslist field is used to tell you which browsers and versions are supported. It is used by Babel, Autoprefixer, and other tools to add the required polyfills and fallbacks to the target browser. For example, the value of this field in the top example:

"browserslist": {
  "production": [
    "0.2%" >."not dead"."not op_mini all"]."development": [
    "last 1 chrome version"."last 1 firefox version"."last 1 safari version"]}Copy the code

This specifies an object that defines the browser requirements for both production and development environments. Development is the last version of Chrome, Firefox, and Safari supported in the development environment. This property is used by many front-end tools, such as Babel, Autoprefixer, etc., to configure the target browser and node version between different front-end tools.