package.json详解

6,051 阅读2分钟

导读

当你通过npm下载一个package的时候,在这个package的根目录下都会有一个package.json文件,这个文件描述了该package的详细信息,比如名称,版本号,作者等。还有些属性是作为开发人员需要熟悉的,下面的属性都是在开发过程中一些常用的属性。

属性列表

dependencies

Dependencies are specified with a simple hash of package name to 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

该属性描述了package的依赖关系,代表package必须在这些依赖的基础上才能正常运行。当你下载package的时候,会同样把package的依赖同样下载下来。

devDependencies

Dependencies are specified with a simple hash of package name to 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

devDependencies下的依赖表示是在开发过程中需要的依赖。与dependencies不同,安装的时候并不会下载里面的依赖。

files

The 'files' field is an array of files to include in your project. If you name a folder in the array, then it will also include the files inside that folder.

当你发布package时,具体那些文件会发布上去呢?就是通过该属性控制的,一般情况下,该属性是这样配置的。

"files": [

"lib"

]

在这种配置情况下,当发布package时,会把lib文件夹发布到npm registry上。

main

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.

该属性描述了一个package的入口。

如果存在一个名字为module-1 的package,在项目中,通过commonjs语法或者是ES6,你可能会这么用。

// ES6
import 'module-1' from 'module-1'
// commonjs
const module-1 = require('module-1')

上面的代码是怎样的执行逻辑呢。

实际情况是这样的,他会从node_modules 中查找是否存在module-1 的packge.如果找到,接着去查看在package路径下是否有index.js, index.json 文件,然后再去寻找packge.json 文件中是否有main 字段。最后根据main 属性配置的信息,找到指定的文件,这样,这个packge就可以正确的加载进来了。

上述情况只是一个简单的描述,实际情况要复杂的多.详细的逻辑请参考 nodejs module

大部分情况下,该属性都是如下配置。

"main": "lib/index.js"

参考链接