npm包的制作与发布使用


制作npm包的步骤

  1. 注册npm账户

    1
    2
    npm adduser

    或者登陆npm官网注册

  2. 登陆npm账户

    1
    2
    npm login

  3. 编写npm包

    • 初始化package.json并配置
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    npm init

    ``````json
    {
    "name": "包名",
    "version": "版本号",
    "description": "描述",
    "main": "入口文件",
    "scripts": {
    "test": "配置测试"
    },
    // 配置git仓库
    "repository": {
    "type": "git",
    "url": "git仓库地址"
    },
    "keywords": [
    "关键字"
    ],
    "author": "",
    "license": "MIT",
    "dependencies": {
    }
    }

  4. 发布

    1
    2
    3
    4
    npm publish
    # 指定标签beta
    npm publish --tag beta

  5. 删除

    1
    2
    npm unpublish --force 包名

  6. 命令行工具包的制作

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    {
    "name": "工具名称",
    "version": "版本号",
    "description": "描述",
    "bin": {
    "命令名称": "命令入口文件"
    },
    "author": "zengyuwen",
    "license": "MIT"
    }

    代码编写

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

代码示例

命令行工具

  • package.json

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    {
    "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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    #!/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));