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"
複製代碼

參考連接

相關文章
相關標籤/搜索