package.json

npm 的 package.json 处理细节

选择 CLI 版本:

描述

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 中最重要的就是名称和版本字段,因为它们是必需的。名称和版本共同构成一个假定完全唯一的标识符。对包的更改应该与版本的更改一起出现。如果你不打算发布你的包,名称和版本字段是可选的。

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 个字符。这包括范围包的范围。

    The name must be less than or equal to 214 characters. This includes the scope for scoped packages.

  • 范围包的名称可以以点或下划线开头。没有范围是不允许的。

    The names of scoped packages can begin with a dot or an underscore. This is not permitted without a scope.

  • 新包的名称中不得包含大写字母。

    New packages must not have uppercase letters in the name.

  • 该名称最终成为 URL、命令行参数和文件夹名称的一部分。因此,名称不能包含任何非 URL 安全字符。

    The name ends up being part of a URL, an argument on the command line, and a folder name. Therefore, the name can't contain any non-URL-safe characters.

一些技巧:

Some tips:

  • 不要使用与核心 Node 模块相同的名称。

    Don't use the same name as a core Node module.

  • 不要在名称中添加 "js" 或 "node"。假设是 js,因为你写的是 package.json 文件,你可以使用 "engines" 字段指定引擎。(见下文。)

    Don't put "js" or "node" in the name. It's assumed that it's js, since you're writing a package.json file, and you can specify the engine using the "engines" field. (See below.)

  • 该名称可能会作为参数传递给 require(),所以它应该是简短的,但也是合理的描述性的。

    The name will probably be passed as an argument to require(), so it should be something short, but also reasonably descriptive.

  • 你可能需要检查 npm 注册表以查看是否已经存在该名称的内容,然后再过分依赖它。https://www.npmjs.com/

    You may want to check the npm registry to see if there's something by that name already, before you get too attached to it. 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 中最重要的就是名称和版本字段,因为它们是必需的。名称和版本共同构成一个假定完全唯一的标识符。对包的更改应该与版本的更改一起出现。如果你不打算发布你的包,名称和版本字段是可选的。

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:

{
"bugs": {
"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

"author" 是一个人。"contributors" 是一组人。"person" 是具有 "name" 字段以及可选的 "url" 和 "email" 的对象,如下所示:

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,直接和间接。提供项目名称时,还可以使用快捷方式访问每个资助网址,例如:npm fund <projectname>(当有多个 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 类似的语法,但相反:包括文件、目录或 glob 模式(***/* 等)将使文件在打包时包含在 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" 字段中的文件

    The file in the "main" field

  • "bin" 字段中的文件

    The file(s) in the "bin" field

README & LICENSE 可以有任何大小写和扩展名。

README & LICENSE can have any case and extension.

默认情况下,某些文件总是被忽略:

Some files are always ignored by default:

  • *.orig

  • .*.swp

  • .DS_Store

  • ._*

  • .git

  • .hg

  • .lock-wscript

  • .npmrc

  • .svn

  • .wafpickle-N

  • CVS

  • config.gypi

  • node_modules

  • npm-debug.log

  • package-lock.json(如果你希望发布,请使用 npm-shrinkwrap.json

    package-lock.json (use npm-shrinkwrap.json if you wish it to be published)

  • pnpm-lock.yaml

  • yarn.lock

如果包含在 files glob 中,则可以专门包含大多数这些被忽略的文件。例外情况是:

Most of these ignored files can be included specifically if included in the files globs. Exceptions to this are:

  • .git

  • .npmrc

  • node_modules

  • package-lock.json

  • pnpm-lock.yaml

  • yarn.lock

这些不能包括在内。

These can not be included.

main

主要字段是模块 ID,它是程序的主要入口点。也就是说,如果你的包名为 foo,并且用户安装了它,然后执行 require("foo"),那么你的主模块的导出对象将被返回。

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

如果你的模块打算在客户端使用,则应使用浏览器字段而不是主字段。这有助于提示用户它可能依赖于 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 字段,它是命令名称到本地文件名的映射。全局安装此软件包时,该文件将链接到全局 bins 目录中,或者将创建一个 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 创建一个运行 cli.js 脚本的 cmd 文件。

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 开头,否则脚本将在没有 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.

Man 文件必须以数字结尾,如果被压缩,还可以选择 .gz 后缀。数字指示文件安装到哪个 man 部分。

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 规范详细介绍了几种使用 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

一个充满手册页的文件夹。Sugar 通过遍历文件夹生成一个 "man" 数组。

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

repository

指定代码所在的位置。这对想要贡献的人很有帮助。如果 git repo 在 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,可以直接交给 VCS 程序而无需任何修改。它不应该是你放在浏览器中的 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

"脚本" 属性是一个字典,其中包含在包生命周期中的不同时间运行的脚本命令。键是生命周期事件,值是要在该点运行的命令。

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

"配置" 对象可用于设置在升级后持续存在的包脚本中使用的配置参数。例如,如果一个包有以下内容:

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

依赖在一个简单的对象中指定,该对象将包名称映射到版本范围。版本范围是一个字符串,它具有一个或多个空格分隔的描述符。依赖也可以使用 tarball 或 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.

请不要将测试工具或转译器或其他 "development" 时间工具放入你的 dependencies 对象中。见下文 devDependencies

Please do not put test harnesses or transpilers or other "development" time tools in your dependencies object. See devDependencies, below.

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

See semver for more details about specifying version ranges.

  • version 必须与 version 完全匹配

    version Must match version exactly

  • >version 必须大于 version

    >version Must be greater than version

  • >=version

    >=version etc

  • <version

  • <=version

  • ~version "大约相当于版本" 见 semver

    ~version "Approximately equivalent to version" See semver

  • ^version "兼容版本" 见 semver

    ^version "Compatible with version" See semver

  • 1.2.x 1.2.0、1.2.1 等,但不是 1.3.0

    1.2.x 1.2.0, 1.2.1, etc., but not 1.3.0

  • http://... 参见下面的 '作为依赖的 URL'

    http://... See 'URLs as Dependencies' below

  • * 匹配任何版本

    * Matches any version

  • ""(只是一个空字符串) 与 * 相同

    "" (just an empty string) Same as *

  • version1 - version2>=version1 <=version2 相同。

    version1 - version2 Same as >=version1 <=version2.

  • range1 || range2 如果满足 range1 或 range2 则通过。

    range1 || range2 Passes if either range1 or range2 are satisfied.

  • git... 参见下面的 '作为依赖的 Git URL'

    git... See 'Git URLs as Dependencies' below

  • user/repo 参见下面的 'GitHub URL'

    user/repo See 'GitHub URLs' below

  • tag 标记并发布为 tag 的特定版本参见 npm dist-tag

    tag A specific version tagged and published as tag See npm dist-tag

  • path/path/path 参见下面的 本地路径

    path/path/path See Local Paths below

例如,这些都是有效的:

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 之一。

<protocol> is one of git, git+ssh, git+http, git+https, or git+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 认为它需要执行构建。为此,你的存储库将被克隆到一个临时目录中,安装其所有 deps,运行相关脚本,并打包并安装生成的目录。

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

从版本 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 your package 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 不会自动安装,如果在树中发现无效版本的对等依赖,则会触发警告。从 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 提供有关如何使用对等依赖的更多信息。具体来说,它允许对等依赖标记为可选。

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.1 中指定。

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 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,同时也使 barfoo 以外的任何深度也成为 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"
}
}
}

当它是包 bar 的子(或孙子,或曾孙等)时,仅将 foo 覆盖为 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 文件夹的每个 工作区

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

    If there is a server.js file in the root of your package, then npm will default the start command to node server.js.

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

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

    If there is a binding.gyp file in the root of your package and you have not defined an install or preinstall script, npm will default the install command to compile using node-gyp.

  • "contributors": [...]

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

    If there is an AUTHORS file in the root of your package, npm will treat each line as a Name <email> (url) format, where email and url are optional. Lines which start with a # or are blank, will be ignored.

SEE ALSO

npm 中文网 - 粤ICP备13048890号