前言
- 不折腾的前端不是一个好的前端,最近在搭建公司内部工具以及组件库,使用
npm
进行管理,所以学习一下如何创建一个属于自己的JavaScript
库,并发布成npm
模块。
步骤
- 创建账号
点击进入npm官网 右上角进行注册
- 创建项目
一路回车或者根据内容填写相关信息后,项目就创建好了。
package.json
内容如下:
- 新建
index.js
文件
(function (root, factory) { 'use strict'; if(typeof define === 'function' && define.amd){ define('log', [], factory); }else{ root['log'] = factory(); }})(this ? this : window, function(){ 'use strict'; const OFF = Number.MAX_VALUE; const DEBUG = 10; const INFO = 20; const WARN = 30; const ERROR = 40; function LogUtil(){ this.consoleLog = window.console; this._level = OFF; } LogUtil.prototype.setLevel = function(level){ if(!level){ return; } level = String(level).toLowerCase(); if(level === 'info'){ level = INFO; }else if(level === 'warn'){ level = WARN; }else if(level === 'error'){ level = ERROR; }else if(level === 'debug'){ level = DEBUG; }else{ level = OFF; } this._level = level; }; LogUtil.prototype.runLog = function(level, methodName, msg){ if(!level){ return; } var form = [new Date().toLocaleString(), level.toLowerCase(), methodName, msg].join('|'); if(level.toLowerCase() === 'debug' && this._level <= DEBUG){ this.consoleLog.debug(form); }else if(level.toLowerCase() === 'info' && this._level <= INFO){ this.consoleLog.info(form); }else if(level.toLowerCase() === 'warn' && this._level <= WARN){ this.consoleLog.warn(form); }else if(level.toLowerCase() === 'error' && this._level <= ERROR){ this.consoleLog.error(form); } }; return LogUtil;});
到这里一个简单的包就创建好了。
如果想再完善一下的话,还可以在包根目录下创建README.md文件,里面可以写一些关于包的介绍信息,最后发布后会展示在NPM官网上。
发布npm
使用终端命令行
如果是第一次发布包,执行以下命令,然后输入前面注册好的NPM账号,密码和邮箱,将提示创建成功
npm adduser
如果不是第一次发布包,执行以下命令进行登录,同样输入NPM账号,密码和邮箱
npm login
注意:npm adduser成功的时候默认你已经登陆了,所以不需要再进行npm login了
接着先进入项目文件夹下,然后输入以下命令进行发布
npm publish
提示如下错误,需要去npm
官网先验证管理员邮箱
后重新发布
说明已经成功
使用
- 添加项目依赖
npm install log-util
- 初始化
//初始化LogUtil对象const log = new LogUtil();//设置默认等级const level = 10;//使用等级log.setLevel(level);
- 具体使用
log.runLog('warn', 'init', 'this is warn log');log.runLog('info', 'init', 'this is info log');log.runLog('debug', 'init', 'this is debug log');log.runLog('error', 'init', 'this is error log');
总结
- 第一次发布npm包,并简单封装了一个
console.log
工具库 - 文章首发于实现一个自己的日志处理库并发布到npm