package.json中的重要属性

导读

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

属性列表

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 URLnode

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

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 URLnpm

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

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.api

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

"files": [

"lib"

]
复制代码

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

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.ui

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

若是存在一个名字为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"
复制代码

参考连接

相关文章
相关标签/搜索