案例:npm包从创建到发布

970 阅读2分钟

npm包从创建到发布

npm项目初始化

在本地磁盘上创建一个空项目,取文件夹名为myNpm。注意请先去npm网官去确定一下,这个项目名是否已经被占用了。(如果这个名字已经被占用了,则你是无法向npm上上传的)。

检查方式为:

npm view 包名
// 这个命令用来查看 某个包的信息
// 如果返回404,说明这个项目名在npm官网上找不到,此时你就可以使用。
// 否则,说明不可用。

完成功能开发

1.png

正常开发,完成你的代码。在默认情况下,index.js是这个项目的入口文件。 下面是一个最简单的示例:

//tools.js
const relativeTime = (oldTime) => {
  const t = new Date(oldTime)
  // Date.now():现在的时间戳(毫秒)
  // t.getTime():旧时间的时间戳(毫秒)

  const diff = Date.now() - t.getTime() // 相隔多少毫秒
  // Math.floor 向下取整: 1.7年 ---> 1年前
  const year = Math.floor(diff / (1000 * 3600 * 24 * 365))
  if (year) {
    return `${year}年前`
  }
  const month = Math.floor(diff / (1000 * 3600 * 24 * 30))
  if (month) {
    return `${month}月前`
  }
  const day = Math.floor(diff / (1000 * 3600 * 24))
  if (day) {
    return `${day}天前`
  }
  const hour = Math.floor(diff / (1000 * 3600))
  if (hour) {
    return `${hour}小时前`
  }
  const minute = Math.floor(diff / (1000 * 60))
  if (minute) {
    return `${minute}分钟前`
  } else {
    return '刚刚'
  }
}

const formatDate = (dateTime) => {
  // console.log(date)
  // date = new Date();
  const date = new Date(dateTime) // 转换成Data();
  console.log(date)
  var y = date.getFullYear()
  console.log(y)
  var m = date.getMonth() + 1
  m = m < 10 ? '0' + m : m
  var d = date.getDate()
  d = d < 10 ? ('0' + d) : d
  return y + '-' + m + '-' + d
}



// 通过module.exports来导出模块
module.exports = {
  formatDate,
  relativeTime
};

切换当前npm镜像源到官网

由于我们需要把包上传到npm上,所以要先确保当前的npm源是npmjs.org。与之相关的命令有如下两条。

查看当前的npm的registry配置.

npm config get registry 
# 查看当前的npm的registry配置,确保是https://registry.npmjs.org

# 如果不是,可以通过如下命令来设置
npm config set registry https://registry.npmjs.org 
# 手动设置registry

连接npm

npm adduser  

这个命令需要输入三个信息以供连接上npmjs:

  • 用户名
  • 密码
  • 邮箱(是你在npmjs官网上注册时使用的信息)

如果你已经不是第一次连接了,这一步是可以省略的。

2.png 你也可以通过如下命令检查自己是否连接成功了。

npm who am i

把包上传到npm

npm publish 

如果成功

-----------------------------------
npm notice
npm notice package: tool61@1.0.0
npm notice === Tarball Contents ===
npm notice 1.3kB index.js
npm notice 220B  package.json
npm notice === Tarball Details ===
npm notice name:          tool61
npm notice version:       1.0.0
npm notice package size:  855 B
npm notice unpacked size: 1.5 kB
npm notice shasum:        3bfba7bc92e242810a850ac39ded7ebe992a6d9c
npm notice integrity:     sha512-VoRuxxbcGzXen[...]v3tKWYUT1B1AQ==
npm notice total files:   2
npm notice
+ tool61@1.0.0

出错的可能是:

  • 这个包名被别人先用了。
  • 包的版本号不对:每次publish时,包的版本号都应该要大于之前的版本号。
  • 文件过大。你可能需要创建.npmignore文件来设置在打包时要忽略哪些文件。如下是一个demo.
# .npmignore
/node_modules
npm-debug.log
/src
/examples
/build

如果没有报错,则表示一切ok,你可以用你的帐号密码登陆npm,去查看你名下的package是否有了myNpm

下载使用

通过npm install 包名即可来安装包。 然后,告诉你的小伙伴们去下载使用吧。

删除包

npm unpublish --force //强制删除

更新包

  1. 修改代码,保存。
  2. 更新版本号。可直接在package.json中修改:只能改大,不能改小。
  3. 重新publish