如何发布自己模块到NPM

创建项目

npm init
name: (my-npm)
version: (1.0.0)
description: 0.0.1
entry point: (index.js)
test command:
git repository:
keywords:
author: Awe
license: (ISC) MIT
About to write to F:\github\my-npm\package.json:

{
  "name": "my-npm",
  "version": "1.0.0",
  "description": "0.0.1",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Awe",
  "license": "MIT"
}
Is this ok? (yes)

接着就依次填写, 不想填写的话也可以一路Enter

  • name:
    模块名,之后发布之后就可以让用户npm install xxxx来引用你的开源模块了
  • version:
    版本号,语义版本号分为X.Y.Z三位,分别代表主版本号、次版本号和补丁版本号。当代码变更时,版本号按以下原则更新。
  • 如果只是修复bug,需要更新Z位。
  • 如果是新增了功能,但是向下兼容,需要更新Y位。

  • 如果有大变动,向下不兼容,需要更新X位。

  • description:
    简单介绍自己的模块

  • main:
    入口文件,必要,当通过require('xxx')时,是读取main里声明的文件

  • test command:
    测试命令

  • git repository:
    git仓库地址

  • keywords:
    关键词,可以通过npm搜索你填写的关键词找到你的模块

  • author:
    作者信息,可以之后编辑更详细一些

  • license(ISC):
    代码授权许可 可以参考这里

以上放心可以大胆写,因为之后反正要改。

初始化项目完成,可以看到目录中出现了一个叫 package.json 的文件

{
  "name": "my-npm",
  "version": "1.0.0",
  "description": "0.0.1",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Awe",
  "license": "MIT"
}

更多配置信息可以参考一下vue的package.json的https://github.com/vuejs/vue/blob/dev/package.json

编写代码

比如我最近写的这个粒子库

class Qarticles {
constructor(canvas, options = {}) {
  this.canvas = canvas
  this.width = options.width || 100
  }
  ...
}

 module.exports = Qarticles

搞定

但是作为一个简单的粒子库,还需要考虑一下标签引入的需求
那么可以在引入的时候判断一下当前被引入的方式
于是我们来构造一个兼容多种引入方式的方法

(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) : (global.Qarticles = factory());

})(this, function () {
  class Qarticles {
    constructor(canvas, options = {}) {
      this.canvas = canvas
      this.width = options.width || 100
    }
    ...
    }
  return Qarticles
})

发布模块

1.在npm 注册用户
2.在本地登录自己的npm账号

npm login  

3.发布模块

npm publish 
//返回下面的信息就是发布成功了 
+ [email protected]

还可以给自己的模块的来个图片徽章,可以放在github仓库的README.md里可以让访问到这项目的人看到项目的状态
http://shields.io/
https://nodei.co/

vue-lazyloadvue-lazyload

附赠:

npm update <package>
//可以把当前目录下node_modules子目录里边的对应模块更新至最新版本。

npm cache clear
//可以清空NPM本地缓存,用于对付使用相同版本号发布新版本代码的人。

npm unpublish <package>@<version>

//可以撤销发布自己发布过的某个版本代码。


转载:
作者:Awe
链接:https://www.jianshu.com/p/f5d4c891830f

猜你喜欢

转载自www.cnblogs.com/yangsg/p/10689348.html