TypeScript 封装并发布一个库

2020-07-05  本文已影响0人  Geeker工作坊

开始之前

使用TypeScript封装一个定时清除localStore的方法。项目中token的信息保存在了localStorage里面了。localStorage中除非手动删除不然就一直留存在浏览器里面。另一个是当token过期时,只有发起一个请求才能感知,如果提前从浏览器中间将要过期的token删除,通知用户重新登录,就能节省一次链接。

NPM 初始化项目

npm init 

根据自己的情况设置 name, version, description, entry point 以及后面的内容。
这里在的entry point 指的是以后使用这个包要引入的文件,不是编译的入口文件


图1

完成后创建一个tsconfig.json的文件

tsc --init

创建完成需要配置几个配置项

  1. "declaration": true, 编译后生成ts声明文件

  2. "outDir": "./dist", 编译后文件输出路径

  3. 在 compilerOption 属性外配置, 在打包的时候排除的文件

    "exclude": [
      "./dist",
    ]
    
  4. 安装 TypeScript 依赖,typescript 只在编译的时候用到

    npm install typescript -D
    

ExpiredStorage 实现

class ExpiredStorage{
    private source:Storage;
    constructor(source:Storage = window.localStorage){
        this.source = source;
        this.initRun();
    }
    initRun(){
        const reg = new RegExp('__expires__');
        let data = this.source;
        let list =  Object.keys(data);
        if(list.length > 0){
            list.map((key, v)=>{
                if(!reg.test(key)){
                    let now  = Date.now();
                    let expire = data[`${key}__expires__`] || Date.now() + 1;
                    if(now >= expire){
                        this.remove(key);
                    }
                }
            })
        }
    }
    set(key:string,value:any,expired:number){
        let source = this.source;
        source[key] = JSON.stringify(value);
        if(expired && expired > 0){
            source[`${key}__expires__`] = Date.now() + expired
        }
    }
    get(key:string):any{
        const source = this.source,
        expired = source[`${key}__expires__`]|| Date.now()+1;
        const now = Date.now();
    
        if ( now >= expired ) {
            this.remove(key);
            return;
        }
        const value = source[key] ? JSON.parse(source[key]) : source[key];
        return value;
    }
    remove(key:string){
        const data = this.source,
            value = data[key];
        delete data[key];
        delete data[`${key}__expires__`];
    }
}

export = ExpiredStorage;

编写完成后在运行 tsc 命令会在根目录下生成 dist 文件夹;js 文件是编译生成的文件,.d.ts是typescript的声明文件。

测试

在根目录下创建测试文件夹 example,创建测试文件,并在tsconfig.json中将该文件添加至 exclude 中。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="../dist/expired-storage.js"></script>
    <script>
        let ls = new ExpiredStorage();
        ls.set('userId','zhangsan',5000);
        window.setInterval(()=>{
            console.log(ls.get("userId"));
        },1000)
    </script>
</body>
</html>

上传至NPM

  1. 首先到NPM网站进行注册
  2. 在控制台下运行 npm login 进行登录
  3. 根目录下添加 .npmignore 文件, 指定要忽略的文件入添加的测试文件夹
    /example
    
  4. 运行 npm publish 发包
上一篇 下一篇

猜你喜欢

热点阅读