一、初始化npm包
npm init
輸入包名后一直回車,直到生成一個package.json,如下
二、新建自己的工具類
這里我建立了一個文件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 Cqh = require("./lib/cqh");
module.exports = {
Cqh
};
四、編寫單元測試
安裝一下依賴包
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 chenqionghe-demo@1.0.1
ok,就是這么簡單,你學會了嗎~