本篇文章承接上文,记录的是如何发布本身的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