本篇文章承接上文,記錄的是如何發佈本身的Node.js模塊node
新建項目並初始化git
$ mkdir 0x005-publish-own-module $ cd 0x005-publish-own-module $ npm init This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sensible defaults. See `npm help json` for definitive documentation on these fields and exactly what they do. Use `npm install <pkg>` afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. package name: (0x005-publish-own-module) version: (1.0.0) description: entry point: (index.js) test command: git repository: keywords: author: license: (ISC) About to write to /MY_PROJECT/PROJECT_OWN/NodeJS/npm/0x005-publish-own-module/package.json: { "name": "0x005-publish-own-module", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" } Is this ok? (yes)
編寫模塊代碼github
$ vim index.js // index.js exports.printMsg = function() { console.log("This is a message from the demo package"); }
發佈模塊npm
$ npm publish --access=public + 0x005-publish-own-module@1.0.0
測試模塊json
$ mkdir 0x006-use-own-package $ cd 0x006-use-own-package $ npm install 0x005-publish-own-module@1.0.0 npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN npm@1.0.0 No description npm WARN npm@1.0.0 No repository field. + 0x005-publish-own-module@1.0.0 $ vim index.js // index.js var myModule = require('0x005-publish-own-module'); console.log(myModule); myModule.printMsg(); $ node index.js { printMsg: [Function] } This is a message from the demo package
每一個人均可以發佈本身的包,不免會有包名相同的狀況,若是想要使用一個已經存在的包的包名,可使用命名空間
將package.json
中的包名該爲@scope/package_name
就行,好比@followwinter/lodash
其中,scope爲當前登陸的用戶名,package_name即是包名,則在安裝、更新、移除、require包的時候都必須該爲這種格式vim
項目的初始化版本號爲1.0.0
,固然也能夠自行修改,也能夠不遵照如下規範segmentfault
主版本號:版本更新,具備顛覆式的改變或者架構的改變架構
次版本號:新功能更新測試
bug修復版本號:bug修復ui
爲一個版本添加一個tag
npm dist-tag add <pkg>@<version> [<tag>]
發佈一個有tag
的版本
npm publish --tag beta --access=public
安裝
npm install 0x005-publish-own-module@beta
0x006 總結
npm publish [[--tag beta] [--access public]]
發佈一個包
若是access=public
,則這個包爲公共的,全部人均可以經過npm
安裝這個包
若是攜帶了tag
參數,則能夠經過npm install <package_name@<tag_name>>
來安裝這個版本的包
npm dist-tag add <pkg>@<version> [<tag>]
爲某個版本添加一個tag