如何開發一個自己的npm包

一、初始化npm包

npm init

運行輸入包名後一直回車,直到生成一個package.json,如下

生成的文件如下

{
  "name": "chenqionghe-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "directories": {
    "lib": "lib",
    "test": "test"
  },
  "dependencies": {
    "assert": "^2.0.0",
    "should": "^13.2.3"
  },
  "devDependencies": {
    "mocha": "^8.0.1"
  },
  "scripts": {
    "test": "mocha"
  },
  "repository": {
    "type": "git",
    "url": "git+//github.com/chenqionghe/npm-demo.git"
  },
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "//github.com/chenqionghe/npm-demo/issues"
  },
  "homepage": "//github.com/chenqionghe/npm-demo#readme"
}

二、新建自己的工具類

這裡我建立了一個文件lib/cqh.js,內容如下

class Cqh {
    hello() {
        console.log('hello chenqionghe')
    }
}

module.exports = Cqh;

三、新建入口文件index.js

默認package.json中指定的入口是index.js,也就是require能用到的東西,我們在index.js里導出一下我們的工具包cqh.js就行了

const Hello = require("./lib/hello");

module.exports = {
    Hello
};

四、編寫單元測試

安裝一下依賴包

npm install mocha assert --save-dev

新建文件test/cqh.js,程式碼如下

/* eslint-env es6 */

const {describe} = require('mocha');
const assert = require('assert');

const {Cqh} = require('../index');

describe('cqh', () => {
    it('hello', async () => {
        let cqh = new Cqh();
        assert("hello chenqionghe", cqh.hello())
    });
});

我們運行一下,斷言成功

五、登錄倉庫

  • 官方倉庫
npm adduser 
  • 私有倉庫
npm adduser --registry 倉庫地址

這裡我登錄的是官方的

六、發布包

  • 官方倉庫
npm publish
  • 私有倉庫
npm publish --registry 倉庫地址

發布如下

登錄官網可以看到已經發布成功了

七、安裝使用

  • 安裝
npm install chenqionghe-demo

  • 測試

新建index.js文件

const {Cqh} = require("chenqionghe-demo");
let cqh = new Cqh();
cqh.hello();

運行如下

八、刪除包

  • 刪除指定版本
npm unpublish 包名@版本號 --force

  • 刪除整個包(慎用、慎用、慎用)
npm unpublish  包名 --force

如果是私有倉庫請加上–registry 倉庫地址

下面演示了刪除1.0.1的版本

npm unpublish [email protected]

ok,就是這麼簡單,你學會了嗎~

Tags: