編寫模塊目錄
-
編寫自己模塊的 package.json
npm init -
package.json 內(nèi)容如下,關(guān)于 package.json 的內(nèi)容編寫可以參考該 文章:
{ "name": "sqlhandler", "version": "0.0.1", "description": "connect to the sqlite3 and simple curd opertaion ", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+ssh://git@github.com/hygfaker/CURDDemo.git" }, "dependencies": { "sqlite3": "^3.1.8" }, "keywords": [ "node.js", "sqlite3", "javascript" ], "author": "yans67", "license": "MIT", "bugs": { "url": "https://github.com/hygfaker/CURDDemo/issues" }, "homepage": "https://github.com/hygfaker/CURDDemo#readme" } -
在目錄中添加 index.js 文件,用于將引用我們寫的模塊。內(nèi)容如下:
module.exports = require('./lib/sqlHandler'); -
創(chuàng)建 lib 目錄,用于存放我們的模塊。
npm.png
上傳到 npm 倉(cāng)庫(kù)
整個(gè)目錄就這樣簡(jiǎn)單地完成了,接下來(lái)就是要將我們的模塊推到 npm 上,供他人使用。
-
在 demo 的根目錄上驗(yàn)證我們的 npm 賬戶,沒(méi)有賬戶的話先到 npm 上 注冊(cè):
npm adduser -
完成驗(yàn)證后,就可以 publish 到 npm 倉(cāng)庫(kù)上。
npm publish
關(guān)于添加依賴時(shí)的版本號(hào)
指定版本:比如1.2.2,遵循“大版本.次要版本.小版本”的格式規(guī)定,安裝時(shí)只安裝指定版本。
波浪號(hào)(tilde)+ 指定版本:比如~1.2.2,表示安裝1.2.x的最新版本(不低于1.2.2)。
插入號(hào)(caret)+ 指定版本:比如?1.2.2,表示安裝1.x.x的最新版本(不低于1.2.2),但是不安裝2.x.x,也就是說(shuō)安裝時(shí)不改變大版本號(hào)。需要注意的是,如果大版本號(hào)為0,則插入號(hào)的行為與波浪號(hào)相同,這是因?yàn)榇藭r(shí)處于開(kāi)發(fā)階段,即使是次要版本號(hào)變動(dòng),也可能帶來(lái)程序的不兼容。
latest:安裝最新版本。
