package.json

npm 的 package.json 处理细节

选择命令行版本:

描述

🌐 Description

这份文档包含了你需要了解的关于 package.json 文件的所有内容。它必须是有效的 JSON,而不仅仅是 JavaScript 对象字面量。

🌐 This document is all you need to know about what's required in your package.json file. It must be actual JSON, not just a JavaScript object literal.

本文档中描述的许多行为都会受到 config 中描述的配置设置的影响。

🌐 A lot of the behavior described in this document is affected by the config settings described in config.

name

如果你打算发布你的包,package.json 中最重要的字段是 name 和 version,因为这是必填字段。name 和 version 一起构成一个被认为是完全唯一的标识符。对包的任何更改都应该伴随版本号的更改。如果你不打算发布你的包,name 和 version 字段则是可选的。

🌐 If you plan to publish your package, the most important things in your package.json are the name and version fields as they will be required. The name and version together form an identifier that is assumed to be completely unique. Changes to the package should come along with changes to the version. If you don't plan to publish your package, the name and version fields are optional.

名字就是你的东西的名字。

🌐 The name is what your thing is called.

一些规则:

🌐 Some rules:

  • 名称必须少于或等于 214 个字符。这包括作用域包的作用域。
  • 带范围的包的名称可以以点或下划线开头。没有范围则不允许这样做。
  • 新包的名称中不得包含大写字母。
  • 这个名称最终会成为 URL 的一部分、命令行参数以及文件夹名称。因此,该名称不能包含任何不安全的 URL 字符。

一些技巧:

🌐 Some tips:

  • 不要使用与核心 Node 模块相同的名称。
  • 不要在名字里加“js”或“node”。默认假设是 js,因为你正在编写 package.json 文件,并且你可以使用“engines”字段来指定引擎。(见下文。)
  • 该名称可能会作为参数传递给 require(),所以它应该是简短的,但也是合理的描述性的。
  • 在你对它太过依赖之前,你可能想先检查一下 npm 注册表,看看是否已经有同名的东西。https://www.npmjs.com/

名称可以选择性地加上作用域前缀,例如 @myorg/mypackage。更多详情请参见 scope

🌐 A name can be optionally prefixed by a scope, e.g. @myorg/mypackage. See scope for more detail.

version

如果你打算发布你的包,package.json 中最重要的字段是 name 和 version,因为这是必填字段。name 和 version 一起构成一个被认为是完全唯一的标识符。对包的任何更改都应该伴随版本号的更改。如果你不打算发布你的包,name 和 version 字段则是可选的。

🌐 If you plan to publish your package, the most important things in your package.json are the name and version fields as they will be required. The name and version together form an identifier that is assumed to be completely unique. Changes to the package should come along with changes to the version. If you don't plan to publish your package, the name and version fields are optional.

版本必须能够被 node-semver 解析,该工具作为依赖打包在 npm 中。(npm install semver 可供你自行使用。)

🌐 Version must be parseable by node-semver, which is bundled with npm as a dependency. (npm install semver to use it yourself.)

description

在其中添加描述。这是一个字符串。这有助于人们发现你的包,因为它会列在 npm search 中。

🌐 Put a description in it. It's a string. This helps people discover your package, as it's listed in npm search.

keywords

在其中放入关键词。它是一个字符串数组。这有助于人们在 npm search 中找到你的包。

🌐 Put keywords in it. It's an array of strings. This helps people discover your package as it's listed in npm search.

homepage

项目主页的 url。

🌐 The url to the project homepage.

示例:

🌐 Example:

"homepage": "https://github.com/owner/project#readme"

bugs

你项目的问题跟踪器的 URL 和/或应报告问题的电子邮件地址。这对遇到你软件包问题的人来说非常有帮助。

🌐 The url to your project's issue tracker and / or the email address to which issues should be reported. These are helpful for people who encounter issues with your package.

它应该如下所示:

🌐 It should look like this:

{
"url": "https://github.com/owner/project/issues",
"email": "project@hostname.com"
}

你可以指定其中一个或两个值。如果你只想提供一个 URL,你可以将“bugs”的值指定为一个简单的字符串,而不是一个对象。

🌐 You can specify either one or both values. If you want to provide only a url, you can specify the value for "bugs" as a simple string instead of an object.

如果提供了 URL,npm bugs 命令将使用它。

🌐 If a url is provided, it will be used by the npm bugs command.

license

你应该为你的包指定一个许可证,以便人们知道他们如何被允许使用它,以及你对其施加的任何限制。

🌐 You should specify a license for your package so that people know how they are permitted to use it, and any restrictions you're placing on it.

如果你使用的是 BSD-2-Clause 或 MIT 等通用许可证,请为你正在使用的许可证添加当前的 SPDX 许可证标识符,如下所示:

🌐 If you're using a common license such as BSD-2-Clause or MIT, add a current SPDX license identifier for the license you're using, like this:

{
"license": "BSD-3-Clause"
}

你可以查看 SPDX 许可证 ID 的完整列表。理想情况下,你应选择一个 OSI 批准的许可证。

🌐 You can check the full list of SPDX license IDs. Ideally you should pick one that is OSI approved.

如果你的软件包在多个常见许可下被许可,请使用 SPDX 许可证表达式语法 2.0 版本字符串,例如:

🌐 If your package is licensed under multiple common licenses, use an SPDX license expression syntax version 2.0 string, like this:

{
"license": "(ISC OR GPL-3.0)"
}

如果你使用的许可证尚未分配 SPDX 标识符,或者如果你使用的是自定义许可证,请使用如下字符串值:

🌐 If you are using a license that hasn't been assigned an SPDX identifier, or if you are using a custom license, use a string value like this one:

{
"license": "SEE LICENSE IN <filename>"
}

然后在包的顶层包含一个名为 <filename> 的文件。

🌐 Then include a file named <filename> at the top level of the package.

一些旧的软件包使用许可证对象或包含许可证对象数组的 "licenses" 属性:

🌐 Some old packages used license objects or a "licenses" property containing an array of license objects:

// Not valid metadata
{
"license" : {
"type" : "ISC",
"url" : "https://opensource.org/licenses/ISC"
}
}
// Not valid metadata
{
"licenses" : [
{
"type": "MIT",
"url": "https://www.opensource.org/licenses/mit-license.php"
},
{
"type": "Apache-2.0",
"url": "https://opensource.org/licenses/apache2.0.php"
}
]
}

这些样式现在已不再使用。请改用 SPDX 表达式,例如:

🌐 Those styles are now deprecated. Instead, use SPDX expressions, like this:

{
"license": "ISC"
}
{
"license": "(MIT OR Apache-2.0)"
}

最后,如果你不希望在任何条款下授予他人使用私有或未发布包的权利:

🌐 Finally, if you do not wish to grant others the right to use a private or unpublished package under any terms:

{
"license": "UNLICENSED"
}

还可以考虑设置 "private": true 以防止意外发布。

🌐 Consider also setting "private": true to prevent accidental publication.

人员字段:作者,贡献者

🌐 people fields: author, contributors

“作者”是一个人。“贡献者”是一个人数组。一个“人”是一个包含“名称”字段的对象,并且可选地包含“网址”和“电子邮件”,如下所示:

🌐 The "author" is one person. "contributors" is an array of people. A "person" is an object with a "name" field and optionally "url" and "email", like this:

{
"name": "Barney Rubble",
"email": "b@rubble.com",
"url": "http://barnyrubble.tumblr.com/"
}

或者你可以将所有内容缩短为一个字符串,npm 将为你解析它:

🌐 Or you can shorten that all into a single string, and npm will parse it for you:

{
"author": "Barney Rubble <b@rubble.com> (http://barnyrubble.tumblr.com/)"
}

email 和 url 都是可选的。

🌐 Both email and url are optional either way.

npm 还会使用你的 npm 用户信息设置一个顶层的 “maintainers” 字段。

🌐 npm also sets a top-level "maintainers" field with your npm user info.

funding

你可以指定一个包含 URL 的对象,该 URL 提供有关帮助资助包开发的方法的最新信息,或字符串 URL,或以下数组:

🌐 You can specify an object containing a URL that provides up-to-date information about ways to help fund development of your package, or a string URL, or an array of these:

{
"funding": {
"type": "individual",
"url": "http://example.com/donate"
},
"funding": {
"type": "patreon",
"url": "https://www.patreon.com/my-account"
},
"funding": "http://example.com/donate",
"funding": [
{
"type": "individual",
"url": "http://example.com/donate"
},
"http://example.com/donateAlso",
{
"type": "patreon",
"url": "https://www.patreon.com/my-account"
}
]
}

用户可以使用 npm fund 子命令列出其项目所有依赖的 funding URL,包括直接和间接依赖。当提供项目名称时,还可以使用快捷方式访问每个资助 URL,例如:npm fund <projectname>(当存在多个 URL 时,将访问第一个 URL)

🌐 Users can use the npm fund subcommand to list the funding URLs of all dependencies of their project, direct and indirect. A shortcut to visit each funding url is also available when providing the project name such as: npm fund <projectname> (when there are multiple URLs, the first one will be visited)

files

可选的 files 字段是一个文件模式数组,用于描述在你的包作为依赖安装时应包含的条目。文件模式采用与 .gitignore 类似的语法,但相反:包括某个文件、目录或通配符模式(***/* 等)将使该文件在打包时包含在 tarball 中。省略该字段将默认使用 ["*"],这意味着它会包含所有文件。

🌐 The optional files field is an array of file patterns that describes the entries to be included when your package is installed as a dependency. File patterns follow a similar syntax to .gitignore, but reversed: including a file, directory, or glob pattern (*, **/*, and such) will make it so that file is included in the tarball when it's packed. Omitting the field will make it default to ["*"], which means it will include all files.

一些特殊的文件和目录也会被包含或排除,无论它们是否存在于 files 数组中(见下文)。

🌐 Some special files and directories are also included or excluded regardless of whether they exist in the files array (see below).

你还可以在包的根目录或子目录中提供一个 .npmignore 文件,它将防止文件被包含。在包的根目录中,它不会覆盖 “files” 字段,但在子目录中会覆盖。.npmignore 文件的工作方式与 .gitignore 一样。如果存在 .gitignore 文件,而 .npmignore 缺失,则会使用 .gitignore 的内容。

🌐 You can also provide a .npmignore file in the root of your package or in subdirectories, which will keep files from being included. At the root of your package it will not override the "files" field, but in subdirectories it will. The .npmignore file works just like a .gitignore. If there is a .gitignore file, and .npmignore is missing, .gitignore's contents will be used instead.

无论设置如何,始终包含某些文件:

🌐 Certain files are always included, regardless of settings:

  • package.json
  • README
  • LICENSE / LICENCE
  • "main" 字段中的文件

READMELICENSE 可以有任何大小写和扩展名。

相反,某些文件总是被忽略:

🌐 Conversely, some files are always ignored:

  • .git
  • CVS
  • .svn
  • .hg
  • .lock-wscript
  • .wafpickle-N
  • .*.swp
  • .DS_Store
  • ._*
  • npm-debug.log
  • .npmrc
  • node_modules
  • config.gypi
  • *.orig
  • package-lock.json(如果你希望发布,可以使用npm-shrinkwrap.json

main

主字段是一个模块 ID,它是你程序的主要入口点。也就是说,如果你的包名为 foo,用户安装它后,再执行 require("foo"),那么将会返回你的主模块的 exports 对象。

🌐 The main field is a module ID that is the primary entry point to your program. That is, if your package is named foo, and a user installs it, and then does require("foo"), then your main module's exports object will be returned.

这应该是相对于包文件夹根目录的模块。

🌐 This should be a module relative to the root of your package folder.

对于大多数模块来说,拥有一个主脚本是最有意义的,而其他的通常不多。

🌐 For most modules, it makes the most sense to have a main script and often not much else.

如果未设置 main,它将在包的根文件夹中默认为 index.js

🌐 If main is not set, it defaults to index.js in the package's root folder.

browser

如果你的模块是用在客户端的,应该使用 browser 字段而不是 main 字段。这有助于提示用户,它可能依赖于 Node.js 模块中不可用的原语。(例如 window

🌐 If your module is meant to be used client-side the browser field should be used instead of the main field. This is helpful to hint users that it might rely on primitives that aren't available in Node.js modules. (e.g. window)

bin

许多软件包都有一个或多个希望安装到 PATH 中的可执行文件。npm 使这一过程相当简单(实际上,它就是利用这个功能来安装 "npm" 可执行文件的)。

🌐 A lot of packages have one or more executable files that they'd like to install into the PATH. npm makes this pretty easy (in fact, it uses this feature to install the "npm" executable.)

要使用此功能,请在你的 package.json 中提供一个 bin 字段,该字段是命令名称到本地文件名的映射。当此包被全局安装时,该文件将被链接到全局 bin 目录中,或者创建一个 cmd(Windows 命令文件),该文件会执行 bin 字段中指定的文件,因此可以通过 namename.cmd(在 Windows PowerShell 中)运行该文件。当此包作为依赖安装到另一个包中时,该文件将在可以被该包直接通过 npm exec 或在其他脚本中通过名称并通过 npm run-script 调用时使用的地方进行链接。

🌐 To use this, supply a bin field in your package.json which is a map of command name to local file name. When this package is installed globally, that file will be either linked inside the global bins directory or a cmd (Windows Command File) will be created which executes the specified file in the bin field, so it is available to run by name or name.cmd (on Windows PowerShell). When this package is installed as a dependency in another package, the file will be linked where it will be available to that package either directly by npm exec or by name in other scripts when invoking them via npm run-script.

例如, myapp 可能有这个:

🌐 For example, myapp could have this:

{
"bin": {
"myapp": "./cli.js"
}
}

所以,当你安装 myapp 时,如果是类 Unix 的操作系统,它会从 cli.js 脚本创建一个到 /usr/local/bin/myapp 的符号链接;如果是 Windows 系统,它通常会在 C:\Users\{Username}\AppData\Roaming\npm\myapp.cmd 创建一个 cmd 文件来运行 cli.js 脚本。

🌐 So, when you install myapp, in case of unix-like OS it'll create a symlink from the cli.js script to /usr/local/bin/myapp and in case of windows it will create a cmd file usually at C:\Users\{Username}\AppData\Roaming\npm\myapp.cmd which runs the cli.js script.

如果你只有一个可执行文件,并且它的名称应该与包名相同,那么你可以直接将其作为字符串提供。例如:

🌐 If you have a single executable, and its name should be the name of the package, then you can just supply it as a string. For example:

{
"name": "my-program",
"version": "1.2.5",
"bin": "./path/to/program"
}

将与此相同:

🌐 would be the same as this:

{
"name": "my-program",
"version": "1.2.5",
"bin": {
"my-program": "./path/to/program"
}
}

请确保你在 bin 中引用的文件以 #!/usr/bin/env node 开头,否则脚本将会在没有节点可执行程序的情况下启动!

🌐 Please make sure that your file(s) referenced in bin starts with #!/usr/bin/env node, otherwise the scripts are started without the node executable!

请注意,你也可以使用 directories.bin 设置可执行文件。

🌐 Note that you can also set the executable files using directories.bin.

有关可执行文件的更多信息,请参见文件夹

🌐 See folders for more info on executables.

man

指定一个文件或一组文件名,以便 man 程序可以找到它们。

🌐 Specify either a single file or an array of filenames to put in place for the man program to find.

如果只提供了一个文件,那么它会被安装为 man <pkgname> 的结果,而不管它的实际文件名。例如:

🌐 If only a single file is provided, then it's installed such that it is the result from man <pkgname>, regardless of its actual filename. For example:

{
"name": "foo",
"version": "1.2.3",
"description": "A packaged foo fooer for fooing foos",
"main": "foo.js",
"man": "./man/doc.1"
}

./man/doc.1 文件链接,使其成为 man foo 的目标

🌐 would link the ./man/doc.1 file in such that it is the target for man foo

如果文件名不是以包名开头的,那么会自动添加前缀。所以,这个:

🌐 If the filename doesn't start with the package name, then it's prefixed. So, this:

{
"name": "foo",
"version": "1.2.3",
"description": "A packaged foo fooer for fooing foos",
"main": "foo.js",
"man": ["./man/foo.1", "./man/bar.1"]
}

将创建文件来执行 man fooman foo-bar

🌐 will create files to do man foo and man foo-bar.

手册文件必须以数字结尾,如果是压缩的,则可以选择性地添加 .gz 后缀。这个数字决定了该手册文件将被安装到哪个手册章节。

🌐 Man files must end with a number, and optionally a .gz suffix if they are compressed. The number dictates which man section the file is installed into.

{
"name": "foo",
"version": "1.2.3",
"description": "A packaged foo fooer for fooing foos",
"main": "foo.js",
"man": ["./man/foo.1", "./man/foo.2"]
}

将为 man fooman 2 foo 创建条目

🌐 will create entries for man foo and man 2 foo

directories

CommonJS Packages 规范详细说明了几种可以使用 directories 对象来指示包结构的方法。如果你查看 npm 的 package.json,你会看到它包含了 doc、lib 和 man 目录。

🌐 The CommonJS Packages spec details a few ways that you can indicate the structure of your package using a directories object. If you look at npm's package.json, you'll see that it has directories for doc, lib, and man.

将来,这些信息可能会以其他创造性的方式使用。

🌐 In the future, this information may be used in other creative ways.

directories.bin

如果你在 directories.bin 中指定了 bin 目录,那个文件夹中的所有文件都会被添加。

🌐 If you specify a bin directory in directories.bin, all the files in that folder will be added.

由于 bin 指令的工作方式,同时指定 bin 路径和设置 directories.bin 是错误的。如果你想指定单个文件,请使用 bin,而对于现有 bin 目录中的所有文件,请使用 directories.bin

🌐 Because of the way the bin directive works, specifying both a bin path and setting directories.bin is an error. If you want to specify individual files, use bin, and for all the files in an existing bin directory, use directories.bin.

directories.man

一个充满手册页的文件夹。通过遍历文件夹生成“man”数组的简便方法。

🌐 A folder that is full of man pages. Sugar to generate a "man" array by walking the folder.

repository

指定你的代码所在的位置。这对想要贡献的人很有帮助。如果 git 仓库在 GitHub 上,那么 npm docs 命令将能够找到你。

🌐 Specify the place where your code lives. This is helpful for people who want to contribute. If the git repo is on GitHub, then the npm docs command will be able to find you.

像这样做:

🌐 Do it like this:

{
"repository": {
"type": "git",
"url": "https://github.com/npm/cli.git"
}
}

URL 应该是一个公开可用的(可能是只读的)URL,可以直接交给版本控制系统程序使用而无需任何修改。它不应该是你在浏览器中打开的 HTML 项目页面的 URL。这是给计算机用的。

🌐 The URL should be a publicly available (perhaps read-only) url that can be handed directly to a VCS program without any modification. It should not be a url to an html project page that you put in your browser. It's for computers.

对于 GitHub、GitHub gist、Bitbucket 或 GitLab 仓库,你可以使用与 npm install 相同的快捷语法:

🌐 For GitHub, GitHub gist, Bitbucket, or GitLab repositories you can use the same shortcut syntax you use for npm install:

{
"repository": "npm/npm",
"repository": "github:user/repo",
"repository": "gist:11081aaa281",
"repository": "bitbucket:user/repo",
"repository": "gitlab:user/repo"
}

如果你的包的 package.json 不在根目录中(例如如果它是 monorepo 的一部分),你可以指定它所在的目录:

🌐 If the package.json for your package is not in the root directory (for example if it is part of a monorepo), you can specify the directory in which it lives:

{
"repository": {
"type": "git",
"url": "https://github.com/facebook/react.git",
"directory": "packages/react-dom"
}
}

scripts

“scripts” 属性是一个字典,包含在你的软件包生命周期的各个阶段运行的脚本命令。键是生命周期事件,值是该阶段要运行的命令。

🌐 The "scripts" property is a dictionary containing script commands that are run at various times in the lifecycle of your package. The key is the lifecycle event, and the value is the command to run at that point.

请参阅 scripts 以了解有关编写软件包脚本的更多信息。

🌐 See scripts to find out more about writing package scripts.

config

可以使用“config”对象来设置在包脚本中使用的配置参数,这些参数在升级过程中会保持不变。例如,如果一个包具有以下内容:

🌐 A "config" object can be used to set configuration parameters used in package scripts that persist across upgrades. For instance, if a package had the following:

{
"name": "foo",
"config": {
"port": "8080"
}
}

它还可以有一个引用了 npm_package_config_port 环境变量的“start”命令。

🌐 It could also have a "start" command that referenced the npm_package_config_port environment variable.

dependencies

依赖在一个简单的对象中指定,该对象将包名称映射到版本范围。版本范围是一个字符串,其中包含一个或多个用空格分隔的描述符。依赖也可以使用 tar 包或 git URL 来标识。

🌐 Dependencies are specified in a simple object that maps a package name to a version range. The version range is a string which has one or more space-separated descriptors. Dependencies can also be identified with a tarball or git URL.

请不要在你的 dependencies 对象中放置测试环境、转译器或其他“开发”时工具。 请参阅下面的 devDependencies

有关指定版本范围的更多详细信息,请参见 semver

🌐 See semver for more details about specifying version ranges.

  • version 必须与 version 完全匹配
  • >version 必须大于 version
  • >=version
  • <version
  • <=version
  • ~version “大致相当于版本” 参见 semver
  • ^version “与版本兼容” 参见 semver
  • 1.2.x 1.2.0、1.2.1 等,但不包括 1.3.0
  • http://... 见下文“作为依赖的 URL”
  • * 匹配任何版本
  • ""(只是一个空字符串)与 * 相同
  • version1 - version2>=version1 <=version2 相同。
  • range1 || range2 如果 range1 或 range2 满足条件则通过。
  • git... 见下文的“作为依赖的 Git URL”
  • user/repo 见下方的“GitHub URL”
  • tag 一个特定版本,被标记并发布为 tag。详见 npm dist-tag
  • path/path/path 请参见下面的 本地路径

例如,这些都是有效的:

🌐 For example, these are all valid:

{
"dependencies": {
"foo": "1.0.0 - 2.9999.9999",
"bar": ">=1.0.2 <2.1.2",
"baz": ">1.0.2 <=2.3.4",
"boo": "2.0.1",
"qux": "<1.0.0 || >=2.3.1 <2.4.5 || >=2.5.2 <3.0.0",
"asd": "http://asdf.com/asdf.tar.gz",
"til": "~1.2",
"elf": "~1.2.3",
"two": "2.x",
"thr": "3.3.x",
"lat": "latest",
"dyl": "file:../dyl"
}
}

作为依赖的 URL

🌐 URLs as Dependencies

你可以指定一个 tarball URL 来代替版本范围。

🌐 You may specify a tarball URL in place of a version range.

此 tarball 将在安装时下载并本地安装到你的包中。

🌐 This tarball will be downloaded and installed locally to your package at install time.

作为依赖的 Git URL

🌐 Git URLs as Dependencies

Git url 的格式为:

🌐 Git urls are of the form:

<protocol>://[<user>[:<password>]@]<hostname>[:<port>][:][/]<path>[#<commit-ish> | #semver:<semver>]

<protocol>gitgit+sshgit+httpgit+httpsgit+file 之一。

如果提供了 #<commit-ish>,将使用它精确克隆该提交。如果 commit-ish 的格式为 #semver:<semver><semver> 可以是任何有效的 semver 范围或确切版本,npm 将在远程仓库中查找与该范围匹配的任何标签或引用,就像处理注册表依赖一样。如果未指定 #<commit-ish>#semver:<semver>,则使用默认分支。

🌐 If #<commit-ish> is provided, it will be used to clone exactly that commit. If the commit-ish has the format #semver:<semver>, <semver> can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. If neither #<commit-ish> or #semver:<semver> is specified, then the default branch is used.

示例:

🌐 Examples:

git+ssh://git@github.com:npm/cli.git#v1.0.27
git+ssh://git@github.com:npm/cli#semver:^5.0
git+https://isaacs@github.com/npm/cli.git
git://github.com/npm/cli.git#v1.0.27

当从 git 仓库安装时,package.json 中某些字段的存在会让 npm 认为需要执行构建。为此,你的仓库将被克隆到一个临时目录,安装所有依赖,运行相关脚本,并打包安装生成的目录。

🌐 When installing from a git repository, the presence of certain fields in the package.json will cause npm to believe it needs to perform a build. To do so your repository will be cloned into a temporary directory, all of its deps installed, relevant scripts run, and the resulting directory packed and installed.

如果你的 git 依赖使用了 workspaces,或者存在以下任何脚本时,将会发生此流程:

🌐 This flow will occur if your git dependency uses workspaces, or if any of the following scripts are present:

  • build
  • prepare
  • prepack
  • preinstall
  • install
  • postinstall

如果你的 git 存储库包含预构建的工件,你可能希望确保没有定义上述脚本,否则将为每次安装重新构建你的依赖。

🌐 If your git repository includes pre-built artifacts, you will likely want to make sure that none of the above scripts are defined, or your dependency will be rebuilt for every installation.

GitHub URL

🌐 GitHub URLs

从版本 1.1.65 起,你可以将 GitHub URL 简化为 "foo": "user/foo-project"。就像使用 git URL 一样,可以添加 commit-ish 后缀。例如:

🌐 As of version 1.1.65, you can refer to GitHub urls as just "foo": "user/foo-project". Just as with git URLs, a commit-ish suffix can be included. For example:

{
"name": "foo",
"version": "0.0.0",
"dependencies": {
"express": "expressjs/express",
"mocha": "mochajs/mocha#4727d357ea",
"module": "user/repo#feature\/branch"
}
}

本地路径

🌐 Local Paths

从版本 2.0.0 开始,你可以提供一个包含软件包的本地目录路径。可以使用 npm install -Snpm install --save 保存本地路径,形式如下:

🌐 As of version 2.0.0 you can provide a path to a local directory that contains a package. Local paths can be saved using npm install -S or npm install --save, using any of these forms:

../foo/bar
~/foo/bar
./foo/bar
/foo/bar

在这种情况下,它们将被规范化为相对路径并添加到你的 package.json 中。例如:

🌐 in which case they will be normalized to a relative path and added to your package.json. For example:

{
"name": "baz",
"dependencies": {
"bar": "file:../foo/bar"
}
}

此功能有助于本地离线开发和创建需要 npm 安装的测试,你不想访问外部服务器,但不应在将包发布到公共注册表时使用。

🌐 This feature is helpful for local offline development and creating tests that require npm installing where you don't want to hit an external server, but should not be used when publishing packages to the public registry.

注意:通过本地路径链接的包在运行 npm install 时不会安装其自身的依赖。在这种情况下,你必须在本地路径内运行 npm install

🌐 note: Packages linked by local path will not have their own dependencies installed when npm install is ran in this case. You must run npm install from inside the local path itself.

devDependencies

如果有人计划在他们的程序中下载和使用你的模块,那么他们可能不想或不需要下载和构建你使用的外部测试或文档框架。

🌐 If someone is planning on downloading and using your module in their program, then they probably don't want or need to download and build the external test or documentation framework that you use.

在这种情况下,最好将这些附加项映射到一个 devDependencies 对象中。

🌐 In this case, it's best to map these additional items in a devDependencies object.

这些内容会在从包的根目录执行 npm linknpm install 时安装,并且可以像管理其他 npm 配置参数一样进行管理。关于此主题的更多信息,请参见 config

🌐 These things will be installed when doing npm link or npm install from the root of a package, and can be managed like any other npm configuration param. See config for more on the topic.

对于不是特定于平台的构建步骤,例如将 CoffeeScript 或其他语言编译为 JavaScript,请使用 prepare 脚本来完成,并将所需的包设为开发依赖(devDependency)。

🌐 For build steps that are not platform-specific, such as compiling CoffeeScript or other languages to JavaScript, use the prepare script to do this, and make the required package a devDependency.

例如:

🌐 For example:

{
"name": "ethopia-waza",
"description": "a delightfully fruity coffee varietal",
"version": "1.2.3",
"devDependencies": {
"coffee-script": "~1.6.3"
},
"scripts": {
"prepare": "coffee -o lib/ -c src/waza.coffee"
},
"main": "lib/waza.js"
}

prepare 脚本将在发布前运行,这样用户可以直接使用功能,而无需自己编译。在开发模式下(即本地运行 npm install),也会运行该脚本,以便你可以轻松测试它。

🌐 The prepare script will be run before publishing, so that users can consume the functionality without requiring them to compile it themselves. In dev mode (ie, locally running npm install), it'll run this script as well, so that you can test it easily.

peerDependencies

在某些情况下,你可能想表达你的软件包与主机工具或库的兼容性,而不一定执行该主机的 require。这通常被称为 插件。值得注意的是,你的模块可能会公开一个特定的接口,该接口由主机文档预期并指定。

🌐 In some cases, you want to express the compatibility of your package with a host tool or library, while not necessarily doing a require of this host. This is usually referred to as a plugin. Notably, your module may be exposing a specific interface, expected and specified by the host documentation.

例如:

🌐 For example:

{
"name": "tea-latte",
"version": "1.3.5",
"peerDependencies": {
"tea": "2.x"
}
}

这确保了你的软件包 tea-latte 只能与主软件包 tea 的第二个主要版本一起安装。npm install tea-latte 可能会产生以下依赖图:

🌐 This ensures your package tea-latte can be installed along with the second major version of the host package tea only. npm install tea-latte could possibly yield the following dependency graph:

├── tea-latte@1.3.5
└── tea@2.2.0

在 npm 版本 3 到 6 中,peerDependencies 不会自动安装,如果在依赖树中发现了无效版本的 peer 依赖,会发出警告。从 npm v7 开始,peerDependencies 默认会被安装。

🌐 In npm versions 3 through 6, peerDependencies were not automatically installed, and would raise a warning if an invalid version of the peer dependency was found in the tree. As of npm v7, peerDependencies are installed by default.

尝试安装具有冲突要求的另一个插件可能会导致错误,如果依赖树不能正确解析。因此,请确保你的插件要求尽可能宽泛,而不是锁定到特定的补丁版本。

🌐 Trying to install another plugin with a conflicting requirement may cause an error if the tree cannot be resolved correctly. For this reason, make sure your plugin requirement is as broad as possible, and not to lock it down to specific patch versions.

假设主机遵循 semver,只有主机软件包的主版本号发生更改才会导致你的插件无法使用。因此,如果你使用过主机软件包的每一个 1.x 版本,可以使用 "^1.0""1.x" 来表示这一点。如果你依赖 1.5.2 中引入的功能,请使用 "^1.5.2"

🌐 Assuming the host complies with semver, only changes in the host package's major version will break your plugin. Thus, if you've worked with every 1.x version of the host package, use "^1.0" or "1.x" to express this. If you depend on features introduced in 1.5.2, use "^1.5.2".

peerDependenciesMeta

当用户安装你的包时,如果 peerDependencies 中指定的包尚未安装,npm 会发出警告。peerDependenciesMeta 字段用于向 npm 提供关于如何使用你的 peer 依赖的更多信息。具体来说,它允许将 peer 依赖标记为可选。

🌐 When a user installs your package, npm will emit warnings if packages specified in peerDependencies are not already installed. The peerDependenciesMeta field serves to provide npm more information on how your peer dependencies are to be used. Specifically, it allows peer dependencies to be marked as optional.

例如:

🌐 For example:

{
"name": "tea-latte",
"version": "1.3.5",
"peerDependencies": {
"tea": "2.x",
"soy-milk": "1.2"
},
"peerDependenciesMeta": {
"soy-milk": {
"optional": true
}
}
}

将同伴依赖标记为可选可以确保如果主机上未安装 soy-milk 包,npm 不会发出警告。这使你可以集成并与各种主机包进行交互,而无需安装所有这些包。

🌐 Marking a peer dependency as optional ensures npm will not emit a warning if the soy-milk package is not installed on the host. This allows you to integrate and interact with a variety of host packages without requiring all of them to be installed.

bundleDependencies

这定义了在发布包时将打包的包名称数组。

🌐 This defines an array of package names that will be bundled when publishing the package.

在需要将 npm 包本地保存或通过单个文件下载获取时,可以通过在 bundleDependencies 数组中指定包名并执行 npm pack,将这些包打包成 tarball 文件。

🌐 In cases where you need to preserve npm packages locally or have them available through a single file download, you can bundle the packages in a tarball file by specifying the package names in the bundleDependencies array and executing npm pack.

例如:

🌐 For example:

如果我们像这样定义一个 package.json:

🌐 If we define a package.json like this:

{
"name": "awesome-web-framework",
"version": "1.0.0",
"bundleDependencies": ["renderized", "super-streams"]
}

我们可以通过运行 npm pack 获取 awesome-web-framework-1.0.0.tgz 文件。该文件包含依赖 renderizedsuper-streams,可以通过执行 npm install awesome-web-framework-1.0.0.tgz 在新项目中安装。请注意,软件包名称不包含任何版本信息,因为这些信息在 dependencies 中已指定。

🌐 we can obtain awesome-web-framework-1.0.0.tgz file by running npm pack. This file contains the dependencies renderized and super-streams which can be installed in a new project by executing npm install awesome-web-framework-1.0.0.tgz. Note that the package names do not include any versions, as that information is specified in dependencies.

如果这个拼写为 "bundledDependencies",那么那个也会被认可。

🌐 If this is spelled "bundledDependencies", then that is also honored.

或者,可以将 "bundleDependencies" 定义为布尔值。true 的值将打包所有依赖,false 的值将不打包任何依赖。

🌐 Alternatively, "bundleDependencies" can be defined as a boolean value. A value of true will bundle all dependencies, a value of false will bundle none.

optionalDependencies

如果可以使用某个依赖,但你希望在找不到或安装失败时 npm 仍然继续,那么你可以将其放入 optionalDependencies 对象中。这是一个从包名到版本或 URL 的映射,就像 dependencies 对象一样。不同之处在于构建失败不会导致安装失败。运行 npm install --omit=optional 将阻止这些依赖被安装。

🌐 If a dependency can be used, but you would like npm to proceed if it cannot be found or fails to install, then you may put it in the optionalDependencies object. This is a map of package name to version or url, just like the dependencies object. The difference is that build failures do not cause installation to fail. Running npm install --omit=optional will prevent these dependencies from being installed.

仍然由你的程序负责处理依赖的缺失。例如,可以这样做:

🌐 It is still your program's responsibility to handle the lack of the dependency. For example, something like this:

try {
var foo = require("foo");
var fooVersion = require("foo/package.json").version;
} catch (er) {
foo = null;
}
if (notGoodFooVersion(fooVersion)) {
foo = null;
}
// .. then later in your program ..
if (foo) {
foo.doFooThings();
}

optionalDependencies 中的条目会覆盖 dependencies 中同名的条目,所以通常最好只放在一个地方。

🌐 Entries in optionalDependencies will override entries of the same name in dependencies, so it's usually best to only put in one place.

overrides

如果你需要对依赖的依赖进行特定更改,例如用已知安全问题替换依赖的版本,用 fork 替换现有依赖,或者确保在任何地方都使用相同版本的包,那么你可以添加一个覆盖。

🌐 If you need to make specific changes to dependencies of your dependencies, for example replacing the version of a dependency with a known security issue, replacing an existing dependency with a fork, or making sure that the same version of a package is used everywhere, then you may add an override.

覆盖(Overrides)提供了一种方法,可以将依赖树中的某个包替换为另一个版本,或完全替换为另一个包。这些更改可以根据需要设置为具体或模糊的范围。

🌐 Overrides provide a way to replace a package in your dependency tree with another version, or another package entirely. These changes can be scoped as specific or as vague as desired.

为了确保无论你的依赖依赖哪个版本,包 foo 都始终安装为版本 1.0.0

🌐 To make sure the package foo is always installed as version 1.0.0 no matter what version your dependencies rely on:

{
"overrides": {
"foo": "1.0.0"
}
}

以上是简写符号,完整的对象形式可以用来覆盖整个包本身以及包的子项。这将导致 foo 始终为 1.0.0,同时在 foo 之后的任意深度处的 bar 也将为 1.0.0

🌐 The above is a short hand notation, the full object form can be used to allow overriding a package itself as well as a child of the package. This will cause foo to always be 1.0.0 while also making bar at any depth beyond foo also 1.0.0:

{
"overrides": {
"foo": {
".": "1.0.0",
"bar": "1.0.0"
}
}
}

仅当 foo 是包 bar 的子级(或孙子级、曾孙级等)时,将其覆盖为 1.0.0

🌐 To only override foo to be 1.0.0 when it's a child (or grandchild, or great grandchild, etc) of the package bar:

{
"overrides": {
"bar": {
"foo": "1.0.0"
}
}
}

键可以嵌套到任意长度。要仅在 foobar 的子级并且仅在 barbaz 的子级时覆盖 foo

🌐 Keys can be nested to any arbitrary length. To override foo only when it's a child of bar and only when bar is a child of baz:

{
"overrides": {
"baz": {
"bar": {
"foo": "1.0.0"
}
}
}
}

覆盖的键也可以包含一个版本或一系列版本。要将 foo 覆盖为 1.0.0,但仅当它是 bar@2.0.0 的子项时:

🌐 The key of an override can also include a version, or range of versions. To override foo to 1.0.0, but only when it's a child of bar@2.0.0:

{
"overrides": {
"bar@2.0.0": {
"foo": "1.0.0"
}
}
}

除非依赖和覆盖本身具有完全相同的规范,否则你不能为你直接依赖的软件包设置覆盖。为了更容易处理此限制,覆盖也可以通过将你希望版本匹配的软件包名称前缀为 $ 的方式定义为对直接依赖规范的引用。

🌐 You may not set an override for a package that you directly depend on unless both the dependency and the override itself share the exact same spec. To make this limitation easier to deal with, overrides may also be defined as a reference to a spec for a direct dependency by prefixing the name of the package you wish the version to match with a $.

{
"dependencies": {
"foo": "^1.0.0"
},
"overrides": {
// BAD, will throw an EOVERRIDE error
// "foo": "^2.0.0"
// GOOD, specs match so override is allowed
// "foo": "^1.0.0"
// BEST, the override is defined as a reference to the dependency
"foo": "$foo",
// the referenced package does not need to match the overridden one
"bar": "$foo"
}
}

engines

你可以指定你的东西适用的 node 版本:

🌐 You can specify the version of node that your stuff works on:

{
"engines": {
"node": ">=0.10.3 <15"
}
}

而且,就像处理依赖一样,如果你没有指定版本(或者你指定了“*”作为版本),那么任何版本的 Node 都可以。

🌐 And, like with dependencies, if you don't specify the version (or if you specify "*" as the version), then any version of node will do.

你也可以使用“engines”字段来指定哪些版本的 npm 能够正确安装你的程序。例如:

🌐 You can also use the "engines" field to specify which versions of npm are capable of properly installing your program. For example:

{
"engines": {
"npm": "~1.0.20"
}
}

除非用户已设置engine-strict 配置标志,否则此字段仅供参考,并且只有在你的包作为依赖安装时才会产生警告。

🌐 Unless the user has set the engine-strict config flag, this field is advisory only and will only produce warnings when your package is installed as a dependency.

os

你可以指定你的模块将在哪些操作系统上运行:

🌐 You can specify which operating systems your module will run on:

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

你也可以选择阻止操作系统而不是允许,只需在被阻止的操作系统前加上'!':

🌐 You can also block instead of allowing operating systems, just prepend the blocked os with a '!':

{
"os": ["!win32"]
}

主操作系统由 process.platform 决定

🌐 The host operating system is determined by process.platform

它既可以阻止也可以允许一个项目,尽管没有任何好的理由这样做。

🌐 It is allowed to both block and allow an item, although there isn't any good reason to do this.

cpu

如果你的代码仅在某些 cpu 架构上运行,你可以指定哪些。

🌐 If your code only runs on certain cpu architectures, you can specify which ones.

{
"cpu": ["x64", "ia32"]
}

os 选项一样,你也可以阻止架构:

🌐 Like the os option, you can also block architectures:

{
"cpu": ["!arm", "!mips"]
}

主机架构由 process.arch 决定

🌐 The host architecture is determined by process.arch

private

如果你在 package.json 中设置了 "private": true,那么 npm 将拒绝发布它。

🌐 If you set "private": true in your package.json, then npm will refuse to publish it.

这是防止意外发布私有仓库的一种方式。如果你想确保某个包只会发布到特定的注册表(例如内部注册表),那么可以使用下面描述的 publishConfig 字典在发布时覆盖 registry 配置参数。

🌐 This is a way to prevent accidental publication of private repositories. If you would like to ensure that a given package is only ever published to a specific registry (for example, an internal registry), then use the publishConfig dictionary described below to override the registry config param at publish-time.

publishConfig

这是一组将在发布时使用的配置值。如果你想设置标签、注册表或访问权限,这特别方便,这样你就可以确保某个包不会被标记为“latest”、发布到公共注册表,或者默认情况下某个作用域模块是私有的。

🌐 This is a set of config values that will be used at publish-time. It's especially handy if you want to set the tag, registry or access, so that you can ensure that a given package is not tagged with "latest", published to the global public registry or that a scoped module is private by default.

请参阅 config 查看可以被覆盖的配置选项列表。

🌐 See config to see the list of config options that can be overridden.

workspaces

可选的 workspaces 字段是一个文件模式数组,用于描述安装客户端应查找的本地文件系统中的位置,以查找每个需要被符号链接到顶层 node_modules 文件夹的 workspace

🌐 The optional workspaces field is an array of file patterns that describes locations within the local file system that the install client should look up to find each workspace that needs to be symlinked to the top level node_modules folder.

它可以描述要用作工作区的文件夹的直接路径,也可以定义将解析为这些相同文件夹的 glob。

🌐 It can describe either the direct paths of the folders to be used as workspaces or it can define globs that will resolve to these same folders.

在以下示例中,位于文件夹 ./packages 内的所有文件夹只要其中包含有效的 package.json 文件,都将被视为工作区:

🌐 In the following example, all folders located inside the folder ./packages will be treated as workspaces as long as they have valid package.json files inside them:

{
"name": "workspace-example",
"workspaces": ["./packages/*"]
}

有关更多示例,请参见workspaces

🌐 See workspaces for more examples.

默认值

🌐 DEFAULT VALUES

npm 将根据包内容默认一些值。

🌐 npm will default some values based on package contents.

  • "scripts": {"start": "node server.js"}

    如果你的包根目录中有一个 server.js 文件,那么 npm 将默认将 start 命令设置为 node server.js

  • "scripts":{"install": "node-gyp rebuild"}

    如果你的包根目录中存在 binding.gyp 文件,并且你没有定义 installpreinstall 脚本,npm 将默认使用 install 命令使用 node-gyp 进行编译。

  • "contributors": [...]

    如果在你的包的根目录中有一个 AUTHORS 文件,npm 会将每一行视为 Name <email> (url) 格式,其中电子邮件和网址是可选的。以 # 开头或空白的行将被忽略。

另见

🌐 SEE ALSO