zoukankan      html  css  js  c++  java
  • 如何开发一个npm包

    一、初始化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,就是这么简单,你学会了吗~

  • 相关阅读:
    mybatis逆向工程
    fastdfs搭建和使用
    solr学习笔记
    自己搭建anki服务器
    redis总结
    java基础——队列
    遍历文件夹下的文件,并且获取文件名字
    xls到xml
    xls文件导入数据库
    PyCharm怎样添加Qt designer
  • 原文地址:https://www.cnblogs.com/chenqionghe/p/13143993.html
Copyright © 2011-2022 走看看