Home > Web Front-end > JS Tutorial > This article will take you to understand package.json in nodejs

This article will take you to understand package.json in nodejs

青灯夜游
Release: 2021-07-15 18:17:40
forward
5161 people have browsed it

This article will take you through the package.json file in the Node.js project, its function, creation method, and how to manage package.json, as well as package.json and package-lock .json difference.

This article will take you to understand package.json in nodejs

With the development of front-end engineering and automation, modular development has become a trend in the current front-end, and in a complete Node.js project, package.json files are everywhere. First, it will be found in the project root directory, and secondly, it will also appear frequently in node_modules. So what is this file for and what role it plays? I will reveal it to you today. [Recommended study: "nodejs Tutorial"]

Package.json file function

When we create a Node.js project, we will encounter the package.json file. It is a JSON file located in the root directory 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) as well as functional metadata (such as the package version number and the list of dependencies required by the program). To fully understand package.json, we have to Let’s start with the Node.js module.

In Node.js, a module can be a library or a framework, or it can be a Node.js project. The Node.js project follows the modular architecture. When we create a Node.js project, The description files for these modules are called package.json files.

package.json is a very important configuration file in the Node.js project. It is the core of a project. This file tracks dependencies and metadata, defines various modules required by the current project, and the project The configuration information is a description of the project or module package, which contains a lot of meta-information.

It defines various dependencies and project configuration information required to run the project (such as project name, project version, project execution entry file, executed scripts, dependent plug-ins, project contributors, licenses, and Information needed to run, develop, and optionally publish your project to npm.).

It is the center for configuring and describing how to interact with and run your program. It is used by npm and yarn to identify your project and understand how to handle the project's dependencies.

npm cli is also the best way to manage package.json as it helps generate and update package.json files throughout the life cycle of the project. The package.json file is a JSON object, and each member of the object is a setting of the current project.

package.json will play multiple roles in the life cycle of the project, some of which are only applicable to packages published to npm. It can start your project, run scripts, install dependencies, publish to npm registry and many other useful tasks. . Even if you don't publish your project to the npm registry or make it publicly available to others, your package.json is still critical to the development process.

Your project must also contain package.json before you can install the package from npm. This is one of the main reasons why you need it in your project.

The npm install command will download all dependent modules based on this file. package.json is generally in the root directory of the project.

package.json file creation

There are two ways to create package.json file, manual creation and automatic creation, generally we use automatic creation More.

1. Create manually

Create the project directory

$mkdir node-demo>cd node-demo>touch package.json
Copy after login

Create a new package.json file directly in the project root directory , and then enter 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": "luyb@xunzhaotech.com",
    "url": "https://www.xunzhaotech.com"
  },
  "contributors": [
    {
      "name": "Amber luyb",
      "email": "luyb@xunzhaotech.com",
      "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 after login

2. Automatically create

When we create a new one named xz-nuxt-admin, at the project root After executing the yarn init -y or npm init -y command in the directory, you can also enter npm init or yarn init -y The command adopts an interactive mode, requiring the user to answer some questions, and then enter the corresponding content step by step according to the prompts. After completion, a basic package.json file will be added in the project directory. Among all questions, only the project name (name) and project version (version) are required, and the others are optional. The content is as follows:

{
 "name": "my-test",   # 项目名称
  "version": "1.0.0", # 项目版本(格式:大版本.次要版本.小版本)
  "author": "",       # 作者
  "description": "",  # 项目描述
  "main": "index.js", # 入口文件
  "scripts": {        # 指定运行脚本命令的 npm 命令行缩写
      "test": "echo \"Error: no test specified\" && exit 1"
  },
"keywords": [],       # 关键词
"license": "ISC"      # 许可证
}
Copy after login

package.json file configuration description

We know some of the most common and important fields contained in package.json, Used to manage a project's configuration information or publish to npm, while others help the npm CLI run applications or install dependencies. There are actually more fields than we've covered, and you can learn about the rest in its documentation, but the following are the package.json properties you must know.

1、必须字段

package.json 中有非常多的配置项,其中必须填写的两个字段分别是 name 字段和 version 字段,它们是组成一个 npm 模块的唯一标识。

name

name 字段定义了模块的名称,其命名时需要遵循官方的一些规范和建议:

  • 项目/模块名称,长度必须小于等于214个字符,不能以"."(点)或者"_"(下划线)开头,不能包含大写字母。
  • 模块名会成为模块 url、命令行中的一个参数或者一个文件夹名称,任何非 url 安全的字符在模块名中都不能使用(我们可以使用 validate-npm-package-name 包来检测模块名是否合法)。
  • 语义化模块名,可以帮助开发者更快的找到需要的模块,并且避免意外获取错误的模块;
  • 若模块名称中存在一些符号,将符号去除后不得与现有的模块名重复。

name 字段不能与其他模块名重复,我们可以执行以下命令查看模块名是否已经被使用:npm view <packageName>或者,我们也可以去 npm 上输入模块名,如果搜不到,则可以使用该模块名。

version

  • 在package.json文件中,版本是非常重要的一个概念,npm 包中的模块版本都需要遵循 SemVer 规范,该规范的标准版本号采用 X.Y.Z 的格式,其中 X、Y 和 Z 均为非负的整数,且禁止在数字前方补零:
  • X 是主版本号(major):第一位就是主要版本号。一般来说,重大功能的更新,或功能的添加又不能向后兼容的情况会提升该版本号。
  • Y 是次版本号(minor):中间那一位是指次要版本号。一般来说,一些功能的添加,但又能向后兼容,这种更新会提升该版本号。
  • Z 是修订号(patch):最后一位就是补丁版本号。一般来说,如果是项目的一些BUG修复,会将该版本号提升。

当某个版本改动比较大、并非稳定而且可能无法满足预期的兼容性需求时,我们可能要先发布一个先行版本。

先行版本号可以加到主版本号.次版本号.修订号的后面,通过 - 号连接一连串以句点分隔的标识符和版本编译信息:

  • 内部版本(alpha)
  • 公测版本(beta)
  • 正式版本的候选版本rc(即 Release candiate)

我们可以执行以下命令查看模块的版本:

$npm view <packageName> version  # 查看某个模块的最新版本
$npm view <packageName> versions # 查看某个模块的所有历史版本
Copy after login

2、可选字段

可选字段是除去必填字段需要补充的项目信息

描述信息(description & keywords)

  • description:字段用于添加模块的描述信息,便于用户了解该模块,是一个字符串。它可以帮助人们在使用npm search时找到这个包。
  • keywords 项目关键字,是一个字符串数组。用于给模块添加关键字。它可以帮助人们在使用npm search时找到这个包。
  • 当我们使用 npm 检索模块时,会对模块中的 description 字段和 keywords 字段进行匹配,写好 package.json中的 description 和 keywords 将有利于增加我们模块的曝光率。

安装项目依赖(dependencies & devDependencies)

  • dependencies:字段指定了项目运行所依赖的模块(生产环境下,项目运行所需依赖)。
  • devDependencies:指定项目开发所需要的模块(开发环境下,项目所需依赖)。

说明:

我们在使用vue框架开发一个程序,开发阶段需要用到webpack来构建你的开发和本地运行环境。所以vue一定要放到dependencies里,因为以后程序到生产环境也要用。webpack则是你用来压缩代码,打包等需要的工具,程序实际运行的时候并不需要,所以放到devDependencies里就可以了。或者我们在写程序要用ES6标准,浏览器并不完全支持,所以你要用到babel来转换代码,babel放devDependencies。程序里有用到开源组件,比如你想用antd,antd要放dependencies。

简化终端命令(scripts)

scripts 字段是 package.json 中的一种元数据功能,它接受一个对象,对象的属性为可以通过 npm run 运行的脚本,值为实际运行的命令(通常是终端命令),如:

  "scripts": {
     "dev": "nuxt",
     "build": "nuxt build",
     "start": "nuxt start",
     "generate": "nuxt generate"
 },
Copy after login

将终端命令放入 scripts 字段,既可以记录它们又可以实现轻松重用。

定义项目入口(main)

main 字段是 package.json 中的另一种元数据功能,它可以用来指定加载的入口文件。假如你的项目是一个 npm 包,当用户安装你的包后,const ModuleName = require('module-name') 返回的是 main 字段中所列出文件的 module.exports 属性。当不指定main 字段时,默认值是模块根目录下面的index.js 文件。

发布文件配置(files)

files 字段用于描述我们使用 npm publish 命令后推送到 npm 服务器的文件列表,如果指定文件夹,则文件夹内的所有内容都会包含进来。我们可以查看下载的 antd 的 package.json 的files 字段,内容如下:

"files": [
   "dist",
   "lib",
   "es"
    ……
],
Copy after login

可以看到下载后的 antd 包是下面的目录结构中包含了 /dist/"lib/es文件,另外,我们还可以通过配置一个 .npmignore 文件来排除一些文件, 防止大量的垃圾文件推送到 npm 上。

定义私有模块(private)

一般公司的非开源项目,都会设置 private 属性的值为 true,这是因为 npm 拒绝发布私有模块,通过设置该字段可以防止私有模块被无意间发布出去。

指定模块适用系统(os)

使用 os 属性可以指定模块适用系统的系统,或者指定不能安装的系统黑名单(当在系统黑名单中的系统中安装模块则会报错)

"os" : [ "darwin", "linux" ] # 适用系统
"os" : [ "!win32" ] # 黑名单
Copy after login

在 node 环境下可以使用 process.platform 来判断操作系统

指定模块适用 cpu 架构(cpu)

我们可以用 cpu 字段更精准的限制用户安装环境

"cpu" : [ "x64", "ia32" ] # 适用 cpu
"cpu" : [ "!arm", "!mips" ] # 黑名单
Copy after login

在 node 环境下可以使用 process.arch 来判断 cpu 架构

指定项目 node 版本(engines)

防止因node 版本不同,导致会出现很多奇奇怪怪的问题(如某些依赖安装报错、依赖安装完项目跑不起来等)。

"engines": {
  "node": ">= 8.16.0",
  "npm": ">= 6.9.0"
},
Copy after login

需要注意的是,engines属性仅起到一个说明的作用,当用户版本不符合指定值时也不影响依赖的安装

自定义命令(bin)

bin 字段用来指定各个内部命令对应的可执行文件的位置。主要应用在脚手架搭建中,当package.json 提供了 bin 字段后,即相当于做了一个命令名和本地文件名的映射。 当用户安装带有 bin 字段的包时,

  • 如果是全局安装,npm 将会使用符号链接把这些文件链接到/usr/local/node_modules/.bin/;
  • 如果是本地安装,会链接到./node_modules/.bin/。

如果要使用 mfd-cli 作为命令时,可以配置以下 bin 字段:

"bin": {
  "mfd-cli": "./bin/cli.js"
  }
Copy after login

上面代码指定,mfd-cli 命令对应的可执行文件为 bin 子目录下的 cli.js,因此在安装了 mfd-cli 包的项目中,就可以很方便地利用 npm执行脚本:

"scripts": {
    start: &#39;node node_modules/.bin/mfd-cli&#39;
 }
Copy after login

这里看起来和 vue create/create-react-app之类的命令不太一样?是因为:当需要 node 环境时就需要加上 node 前缀如果加上 node 前缀,就需要指定mfd-cli 的路径 -> node_modules/.bin,否则 node mfd-cli会去查找当前路径下的 mfd-cli.js,这样肯定是不对。若要实现像 vue create/create-react-app之类的命令一样简便的方式,则可以在上文提到的 bin 子目录下可执行文件cli.js 中的第一行写入以下命令:#!/usr/bin/env node这行命令的作用是告诉系统用 node 解析,这样命令就可以简写成 mfd-cli 了。

设置应用根路径(homepage)

当我们使用 create-react-app 脚手架搭建的 React 项目,默认是使用内置的 webpack 配置,当package.json 中不配置 homepage 属性时,build 打包之后的文件资源应用路径默认是/

一般来说,我们打包的静态资源会部署在 CDN 上,为了让我们的应用知道去哪里加载资源,则需要我们设置一个根路径,这时可以通过 package.json 中的 homepage 字段设置应用的根路径。

当我们设置了 homepage 属性后:

{
    "homepage": "https://xxxx.cdn/project-name",
}
Copy after login

打包后的资源路径就会加上 homepage 的地址:/project-name/bundle.js

Other configuration

  • author: project developer, its value is your valid account name on the npmjs.org website, follow the "Account Name ” rules, for example: xunzhaotech@aliyun.com.
  • private: Whether it is private. When set to true, npm refuses to publish.
  • license: Software licensing terms to let users know their usage rights and restrictions.
  • bugs: bug submission address.
  • contributors: project contributors.
  • repository: Project warehouse address.
  • module: It is loaded in the ES Module (that is, ES6) modular way, because when there was no ES6 modular solution in the early days, it all followed the CommonJS specification, and the package of the CommonJS specification expressed the entry in the form of main. In order to distinguish the file, the module method is added, but the ES6 modular solution is more efficient, so it will first check whether there is a module field, and only use the main field if not.
  • eslintConfig: EsLint checks the file configuration and automatically reads the verification.
  • browserslist: A list of versions for browsers to use.
  • style: The location of the style file when used by the browser; the style file packaging tool parcelify knows the packaging location of the style file.

The difference between package.json and package-lock.json

Why do you need the package-lock.json file when you have package.json? When the node_modules folder does not exist or is deleted, and you need to use npm install to reload all dependencies, you can directly indicate the download address and related dependencies through package-lock.json. The download speed is also faster and it is not easy to report errors.

For more programming related knowledge, please visit: Programming Video! !

The above is the detailed content of This article will take you to understand package.json in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:掘金--快智岛
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template