npm包的制作与发布使用

 后端   大苹果   2018-05-22 11:19   1890
  npm

制作npm包的步骤

  1. 注册npm账户

    npm adduser
    

    或者登陆npm官网注册

  2. 登陆npm账户

    npm login
    
  3. 编写npm包

    • 初始化package.json并配置
    npm init
    
    {
        "name": "包名",
        "version": "版本号",
        "description": "描述",
        "main": "入口文件",
        "scripts": {
            "test": "配置测试"
        },
        // 配置git仓库
        "repository": {
            "type": "git",
            "url": "git仓库地址"
        },
        "keywords": [
            "关键字"
        ],
        "author": "",
        "license": "MIT",
        "dependencies": {
        }
    }
    
  4. 发布

    npm publish
    # 指定标签beta
    npm publish --tag beta
    
  5. 删除

    npm unpublish --force 包名
    
  6. 命令行工具包的制作

    {
        "name": "工具名称",
        "version": "版本号",
        "description": "描述",
        "bin": {
            "命令名称": "命令入口文件"
        },
        "author": "zengyuwen",
        "license": "MIT"
    }
    

    代码编写

    #!/usr/bin/env node
    // 获取命令行参数
    const arguments = process.argv.splice(2);
    

代码示例

命令行工具

  • package.json

    {
        "name": "cli",
        "version": "1.0.0",
        "description": "",
        "main": "index.js",
        "scripts": {
            "test": "echo \"Error: no test specified\" && exit 1"
        },
        "bin": {
            "my-cli": "./index.js"
        },
        "author": "",
        "license": "ISC"
    }
    
  • index.js

    #!/usr/bin/env node
    // 获取命令行参数
    const arguments = process.argv.splice(2);
    // 参数解析成数组
    function parse(arguments) {
        return arguments.map(function(value) {
            if (/^-+/.test(value)) {
                return value.replace(/^-+/, '');
            }
            return value;
        });
    }
    // 参数解析成键值对
    function parseObj(arguments) {
        let result = [];
        for (let i = 0;i < arguments.length; i+= 2) {
            tmp = {};
            if ((i + 1) >= arguments.length) {
                tmp[arguments[i].replace(/^-+/, '')] = null;
            } else {
                tmp[arguments[i].replace(/^-+/, '')] = arguments[i+1];
            }
            result.push(tmp);
        }
        return result;
    }
    // 求和
    function add(arguments) {
        var params = parse(arguments);
        var result = 0;
        for (let i of params) {
            if (/^[0-9]{1,}$/.test(i)) {
                result += parseInt(i);
            }
        }
        return result;
    }
    console.log(parseObj(arguments));
    console.log(add(arguments));