The latest and most complete guide to package.json that must be mastered by the middle and advanced front end.

June 20, 2023 1358hotness 0likes 0comments

Preface

package.json is an important file for describing and configuring a project, which contains a number of fields and options that can affect project construction, dependency management, script execution, and so on. Understanding these fields can help developers better understand and control the behavior of the project.

package.json for most front-end developers, knowing dependencies and devDependencies is enough. However, for library developers or developers with more advanced needs, it is necessary to understand the other fields of package.json.

the fields introduced in this article are divided into official fields and unofficial fields. Unofficial fields are supported by mainstream packaging tools (webpack,Rollup) and are designed to provide more advanced configuration and functionality to meet specific build needs and may not be universal.

current version: v7.24.2

I. required attribute

1. name

defines the name of the project, not with "." Start with "_" and cannot contain uppercase letters

2. version

defines the version number of the project in the format of large version number. The second edition number. Revision number

II. Description information

1. description

Project description

2. keywords

Project keywords

3. author

Project author

"author": "name (http://barnyrubble.tumblr.com/)"

4. contributors

Project contributor

  "contributors": [
    "name <[email protected]> (http://barnyrubble.tumblr.com/)"
  ]

5. homepage

Project home page address

6. repository

Project Code Warehouse address

7. bugs

address of project submission question

 // address for submitting questions and email address for feedback. Url is usually the issues page in Github.
"bugs": { 
  "url" : "https://github.com/facebook/react/issues", 
  "email" : "[email protected]"
}

8. funding

specify the financial support method and link for the project

  "funding": {
    "type": "patreon",
    "url": "https://www.patreon.com/my-module"
  }

III. Dependency configuration

1. dependencies

dependency packages for production environments

if you do not use delimiting (^), the version number of the installation is fixed; if you use it, you can install the latest version of the current large version, and you can view the actual installed version in package-lock.json.

2. devDependencies

dependency packages for the development environment, such as webpack, vite, babel, ESLint, and so on.

3. peerDependencies

role of peer dependency:

  1. reduce the package size: for example, using the component library developed by react, installing react is essential, while developers using the component library must have installed react in the local project, so there is no need to package react in the developed component library (expect the users of the project to provide the implementation of these modules).

  2. version consistency: developers using your component library need to ensure that packages compatible with your declared peer-dependent version are installed in their projects to ensure that the library works properly.

example: to declare that you want to use the component library, you need to install react greater than 17.0.1 in the project

  "peerDependencies": {
    "react": ">17.0.1"
  }

4. peerDependenciesMeta

Mark peer dependency as optional. If the user does not have peer dependency installed, npm will not issue a warning

  "peerDependenciesMeta": {
    "react": {
      "optional": true // Mark as optional
    }
  }

5. bundledDependencies

declare bundled dependencies (fewer usage scenarios)

6. optionalDependencies

declare optional dependencies (fewer usage scenarios)

7. engines

declare the version requirements for npm or node

  "engines": {
    "node": ">=8.10.3 <12.13.0",
    "npm": ">=6.9.0"
  }

engines is for illustrative purposes only, and does not affect the installation of dependency packages even if the version installed by the user does not meet the requirements.

8. workspaces

multiple packages (monorepo) are managed uniformly in a single code library, and the package under the workspaces declaration directory will be soft-linked to the node_modules in the root directory.

1. Initialize the project

npm init -y

2. Declare that this project is in workspaces mode

  "private":"true",
  "workspaces": [
    "packages/*" 
  ],

indicates that all subpackages are under the packages folder

3. Create subpackage p1

npm init -w packages/p1 -y

you can see "link": true link symbol information in node_modules/.package-lock.json

4. Create a new packages/p1/index.js

module.exports = "p1 package";

5. Create subpackage p2

npm init -w packages/p2 -y

6. Add subpackage p1 to p2

npm i p1 -w p2

install, uninstall and other commands are all the same, except that the "--workspace=" parameter (abbreviated-w) is added to specify which package to execute the command

7. Subpackage p2 uses p1

const p1 = require("p1");

console.log("use", p1);

module.exports = "p2 package";

workspaces is similar to lerna in that workspaces is sufficient if you simply manage multiple packages. Lerna has more functions such as version management, sending prompts, simplifying the release process of multi-package projects, and so on.

IV. Script configuration

1. scripts

script entry

2. config

is used to define the configuration items of the project, such as setting environment variables

1. Config configuration

  "config": {
    "baseUrl": "https://example.com"
  }

2. Scripts configuration

  "scripts": {
    "start": "node index.js",
  },

3. Create a new index.js

// use process.env.npm_package_config_XXX to take a value
console.log(process.env.npm_package_config_baseUrl)

run npm run start, and the terminal prints out example.com

V. File & directory

1. Module (unofficial field)

specify the ES module entry file

example: when other developers import your package in their project, the dist/index.esm.js in the package will be loaded and executed

"main": "dist/index.esm.js"

2. main

specify the CommonJS module or ES module entry file. If this field is not specified, the default is index.js

in the root directory.

Tip: starting from Node.js 12.20.0, the "main" field can also specify the entry file of the ES module

3. browser

specify the entry file used by the browser, such as the umd module.

4. Types (unofficial field)

specify the path to the TypeScript type declaration file (.d.ts file)

5. Exports (unofficial field)

when the packaging tool supports exports fields (webpack, Rollup, etc.), the above four main,browser,module,types fields are ignored

"." Indicates the default export

"import": the path to the exported file under the ES module (ESM) specification is specified

"require": the path to the exported file under the CommonJS specification is specified

"browser": export file path specified for browser environment

"types": the path to the type declaration file is specified

  "exports": {
    ".": {
      "import": "./dist/index.esm.js",
      "require": "./dist/index.cjs.js",
      "browser": "./dist/index.umd.js",
      "types": "./dist/index.d.ts"
    }
  }

Export other files, for example, export source files in addition to the default path

  "exports":{
    ...
  "./main" : "./src/main.js"
},

use

in other projects

import main from 'packageName'; //. Mode defined
import main from 'packageName/main'; //. / defined in main mode

6. Type (unofficial field)

specify how to use the module system, "commonjs", "module", "umd", "json"

example: specify that the module system is in ES module mode. When using CommonJS files, you need to explicitly define them as .cjs file extension to specify these files as CommonJS modules

"type":"module"

7. files

specify which packages are pushed to the npm server

example: only index.js and dist packages are pushed to the npm server

  "files": [
    "index.js",
    "dist"
  ],

you can create a new .npmsubmission file in the root directory of the project, indicating that you do not need to submit files to the npm server, similar to .gitignore. Files written in this file will be excluded even if they are written in the files attribute

8. bin

define commands that can be executed during global installation (with fewer usage scenarios)

9. man

help instructions in Linux (fewer usage scenarios)

10. directories

Fields that define the project directory structure (fewer usage scenarios)

VI. Release configuration

1. private

prevent private packages from being published to npm servers. To publish to npm, set it to false

2. PreferGlobal (unofficial field)

when you set the "preferGlobal" field to true, it indicates that your package is more suitable for global installation than local installation as a dependency of the project.

The

field is set to give users advice on the best way to use your package. It does not directly affect how the package is installed or the behavior of the package manager.

3. publishConfig

specify a specific configuration when publishing the package

example: specify the registry URL published by the package, and specify that all users can access it (private ones will be charged)

  "publishConfig": {
    "registry": "https://registry.npmjs.org/",
    "access": "public"
  }

4. os

specify the operating system for your package

example: package is only available for darwin (macOS) and linux

"os": ["darwin", "linux"]

example: disable win32

"os" ["!win32"] // disabled operating system

5. cpu

this configuration is similar to OS configuration, and CPU can more accurately limit the user's installation environment

.

6. license

specify the open source protocol for the software:

ISC: keep the copyright notice and license notice in all copies so that users can do whatever they want with your code, and you don't have to bear any responsibility

MIT: keep the copyright notice and license notice in all copies or major sections so that users can do whatever they want with your code, and you don't have to bear any responsibility

Open source protocol query address: opensource.org/licenses/

VII. Third-party configuration (unofficial field)

1. eslintConfig

configuration of eslint. It is recommended to create a new .eslintrc to configure

2. babel

babel configuration, it is recommended to create a new babelrc for configuration

3. unpkg

unpkg is a CDN-based front-end package hosting service that references and loads packages published on npm directly in the browser.

reference

directly through the & lt;script> tag without downloading.

<script src="https://unpkg.com/package-name@version"></script>

4. lint-staged

lint-staged is a tool for running linters on Git staging files, usually with gitHooks.

5. browserslist

tells which browsers and versions are supported, which are commonly used by Autoprefixer

  "browserslist": [
    "defaults",
    "not ie < 8",
    "last 2 versions",
    "> 1%",
    "iOS 7",
    "last 3 iOS versions"
  ]

6. sideEffects

indicates whether the package has side effects, and assists Webpack,Rollup to tree shaking

.

in most cases, it can be directly set to false, so that the packaging tool will automatically delete the code that has not been import

but there are some exceptions

  1. there are specific module files that perform side effects, such as registering global event listeners, modifying global state, and so on.

  2. tell the build tool not to exclude style files from the optimization scope of useless code elimination

"sideEffects": ["./path/to/module.js", "*.css"]
InterServer Web Hosting and VPS

Aaron

Hello, my name is Aaron and I am a freelance front-end developer

Comments