實現一個本身的日誌處理庫併發布到npm

前言

  • 不折騰的前端不是一個好的前端,最近在搭建公司內部工具以及組件庫,使用npm進行管理,因此學習一下如何建立一個屬於本身的JavaScript庫,併發布成npm模塊。
  • https://github.com/ahwgs/cons...

步驟

  • 建立帳號

點擊進入npm官網 右上角進行註冊javascript

  • 建立項目

一路回車或者根據內容填寫相關信息後,項目就建立好了。html

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官網上。java

發佈npm

使用終端命令行
若是是第一次發佈包,執行如下命令,而後輸入前面註冊好的NPM帳號,密碼和郵箱,將提示建立成功git

npm adduser

若是不是第一次發佈包,執行如下命令進行登陸,一樣輸入NPM帳號,密碼和郵箱github

npm login

注意:npm adduser成功的時候默認你已經登錄了,因此不須要再進行npm login了npm

接着先進入項目文件夾下,而後輸入如下命令進行發佈json

npm publish

提示以下錯誤,須要去npm官網先驗證管理員郵箱

後從新發布bash

說明已經成功併發

使用

  • 添加項目依賴
npm install console-util

  • 具體使用
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="../release/index.js"></script>
<script>
    window.onload = function () {
        //初始化LogUtil對象
        let log = new LogUtil();
        //設置默認等級
        let level = 'info';
        //使用等級
        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');
    }
</script>
</body>
</html>

總結

相關文章
相關標籤/搜索