从0开发一个自己的npm包

之前写过一些npm包,但是每次都会忘记具体流程,今天做个简单记录。

一、注册npm账号

https://www.npmjs.com

二、开发自己的npm包

1. 初始化npm包

npm init

生成package.json文件

{
  "name": "create-random-value",
  "version": "1.0.0",
  "description": "通过传参生成指定长度的随机字符串",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "random",
    "string",
    "node",
    "vue"
  ],
  "author": "fujinting",
  "license": "ISC"
}

2. 开发npm包
"use strict";

const number = "123467890";
const bigLetter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const smallLetter = "abcdefghijklmnopqrstuvwxyz";
const punctuation = "~!@#$%^&*()_+-=[]{}|;:,./<>?";

function random(length, option) {
  let char = "";
  let result = "";

  length || (length = 8);
  option || (option = {});

  if (option === true) {
    char = number + bigLetter + smallLetter + punctuation;
  } else if (typeof option == "string") {
    char = option;
  } else {
    if (option.number !== false) {
      char += typeof option.number == "string" ? option.number : number;
    }

    if (option.bigLetter !== false) {
      char +=
        typeof option.bigLetter == "string" ? option.bigLetter : bigLetter;
    }
    if (option.smallLetter !== false) {
      char +=
        typeof option.smallLetter == "string"
          ? option.smallLetter
          : smallLetter;
    }

    if (option.punctuation) {
      char +=
        typeof option.punctuation == "string"
          ? option.punctuation
          : punctuation;
    }
  }

  while (length > 0) {
    length--;
    result += char[Math.floor(Math.random() * char.length)];
  }
  return result;
}
module.exports = random;

这是一个根据传入的参数,生成随机字符串的插件,使用文档下篇文章会给出,大家也可以下载使用下。

三、 上传npm包

如果你是第一次开发npm包,需要 npm adduser

当然我不是,所以我只需要 npm login 就可以了

输入 username,password ,email,这时候保证自己的npm源(镜像)是npm官方自己的 https://registry.npmjs.org/,不是请 切换 哦,否则报错提示。

接下来使用命令发布这个包

npm publish

四、检查看看

在这里插入图片描述

在这里插入图片描述
success!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值