导读
当你通过 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"
参考链接
- nodejs
- npm packge.json
来源: https://juejin.im/post/5a9f4721518825555e5d5d3e