如何開發一個npm包併發布

1、安裝nodejs

很少說了,網上教程多得是javascript

2、建立本身的npm包

目錄結構

  • npm-test
    • a.js
    • b.js
    • package.json

開發

爲了簡單便於理解,就開發一個簡單地hello程序java

a.jsnode

function hello(name){
  console.log("hello "+ name);
}
exports.hello=hello;

b.jsnpm

var h=require('./a');
h.hello('Jarrick');

使用命令npm init建立一個package.jsonjson

{
  "name": "qzy-npm-test",
  "version": "1.0.1",
  "description": "npm包開發測試",
  "main": "a.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": "",
  "keywords": [
    "qzy",
    "npm-test"
  ],
  "author": "quanzaiyu",
  "license": "ISC"
}

3、發佈npm包

首先,必須註冊一個npm帳號,本身去 https://www.npmjs.com 註冊便可。此處很少說bash

添加帳戶

npm adduser

填入本身的npm帳戶名、密碼和郵箱便可測試

發佈npm包

npm publish

進入npm我的中心,能夠看到本身的npm包已經發布在上面了ui

獲取npm包

npm install <package-name>

此處package-name使用qzy-npm-test便可
能夠看到,多了一個node_modules目錄,裏面多了一個qzy-npm-test文件夾,裏面放的就是咱們剛纔建立的npm包,包含a.js、b.js、package.json三個文件this

使用npm包

跟使用普通的npm包同樣,問了測試簡單,建立一個index.js,輸入debug

let a = require('qzy-npm-test')
a.hello('qzy')

執行node index便可看見輸出了hello qzy

更新npm包

更新npm包也是使用npm publish命令發佈,不過必須更改npm包的版本號,即package.json的version字段,不然會報錯:

npm ERR! publish Failed PUT 403
npm ERR! code E403
npm ERR! You cannot publish over the previously published version 1.0.0. : qzy-npm-test

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\quanzaiyu\AppData\Roaming\npm-cache\_logs\2017-09-12T07_59_18_829Z-debug.log

成功以後的提示:

λ npm publish
+ qzy-npm-test@1.0.1
相關文章
相關標籤/搜索