如何上传发布自己的npm组件包

本文介绍如果上传自己写的 npm 组件包到 npm私库上。当你 写好了自己的一个npm的组件想共享上去给别人或者给公司的同事使用的时候,你可以把你的npm组件发布上去 (publish)。不过npm的全局库估计你是上传不上去的,要经过审核,但是你可以上传到你自己公司的私库,搭建私库的教程可以参见 http://blog.csdn.net/nsrainbow/article/details/35989657


前提条件:

  1. 你已经建好了一个公司的私库,这个私库地址是 http://localhost:5984/registry/_design/scratch/_rewrite
  2. 你为这个私库设置了用户名 admin 密码 123456

STEP1 修改.npmrc

在自己的home目录下看看有没有.npmrc 这个文件存在,如果没有的话增加一个,如果你是在 linux 下则运行

[plain] view plain copy

  1. $ vim ~/.npmrc



并编辑这个文件的内容

[plain] view plain copy

  1. registry = http://admin:123456@localhost:5984/registry/_design/scratch/_rewrite


前面的 admin:123456 是用户名密码

STEP2 建立一个测试项目

[plain] view plain copy

  1. $ mkdir testmypublish
  2. $ cd testmypublish
  3. $ vim package.json


把以下内容粘贴进去

[plain] view plain copy

  1. {
  2. "name": "testmypublish",
  3. "version": "0.0.1",
  4. "repository" :
  5. { "type" : "git"
  6. , "url" : "https://github.com/<yourusername>/testmypublish.git"
  7. }
  8. }


这边声明以下,那个 repository 属性不写也可以,但是最好建一个 github 项目然后把地址写进来,这样会比较规范。没有github账号的朋友就别写这段了直接写成

[plain] view plain copy

  1. {
  2. "name": "testmypublish",
  3. "version": "0.0.1"
  4. }

就行

STEP3 添加npm用户

[plain] view plain copy

  1. $ npm adduser
  2. Username: alex
  3. Password:
  4. Email: (this IS public) Alex.Yang@ehealth.com


STEP 4 登陆刚刚建立的用户

[plain] view plain copy

  1. npm login
  2. Username: (alex)
  3. Password: (or leave unchanged)
  4. Email: (this IS public) (Alex.Yang@ehealth.com)


问username password email的时候一路回车就好

STEP 5 发布项目

[plain] view plain copy

  1. $ cd testmypublish
  2. $ npm publish
  3. + testmypublish@0.0.1


这就发布完成了


客户端测试

[plain] view plain copy

  1. $ npm install testmypublish

  2. 长按图片识别图中二维码(或搜索微信公众号FrontEndStory)关注“前端那些事儿”,带你了解最新的前端技术。