TypeScript封装插件
更新时间: 2023-03-03 15:38:12
# 思路
写一个localStorage库,在存储数据的时候可以设置一个过期时间,当读取的时候获取当前时间进行判断是否过期,如果过期了就进行删除,localStorage原本是不支持过期时间的,我们可以实现它。
# 目录结构
├── dist // 打包的目录
│ └── index.js // 打包的文件
├── src
│ ├── enum // 定义枚举的文件夹
│ │ └── index.ts
│ ├── types // 定义类型的文件夹
│ │ └── index.ts
│ └── index.ts // 主要逻辑写在这里
├── index.html // 测试html
├── package.json
├── rollup.config.js
└── tsconfig.json
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 配置
# tsconfig.json
运行 tsc --init
生成tsconfig.json文件,并将高亮部分的配置修改如下
{
"compilerOptions": {
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"module": "ESNext", /* Specify what module code is generated. */
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": false, /* Enable all strict type-checking options. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 安装依赖并修改package.json配置
安装 rollup
, rollup-plugin-typescript2
, typescript
npm i rollup rollup-plugin-typescript2 typescript -D
然后修改配置:
{
"name": "ts-study",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type":"module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "rollup -c"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"rollup": "^3.18.0",
"rollup-plugin-typescript2": "^0.31.1",
"typescript": "^4.5.5"
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# rollup.config.js
import path from "path"
import ts from "rollup-plugin-typescript2"
import {fileURLToPath} from 'url'
const metaUrl = fileURLToPath(import.meta.url)
const dirName = path.dirname(metaUrl) //得到正确的根目录
export default {
input:"./src/index.ts",
output:{
file:path.resolve(dirName,"./dist/index.js")
},
plugins:[
ts() // 解析ts
]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 代码实现
# 定义枚举
// enum/index.ts
//字典 Dictionaries expire过期时间key permanent永久不过期
export enum Dictionaries {
expire = '__expire__',
permanent = 'permanent'
}
1
2
3
4
5
6
2
3
4
5
6
# 定义类型
import { Dictionaries } from "../enum"
export type Key = string //key类型
export type expire = Dictionaries.permanent | number //有效期类型
export interface Data<T> { //格式化data类型
value: T
[Dictionaries.expire]: Dictionaries.expire | number
}
export interface Result<T> { //返回值类型
message: string,
value: T | null
}
export interface StorageCls { //class方法约束
set: <T>(key: Key, value: T, expire: expire) => void
get: <T>(key: Key) => Result<T | null>
remove: (key: Key) => void
clear: () => void
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# index.ts主要逻辑实现
import { StorageCls, Key, expire, Data,Result } from "./type";
import { Dictionaries } from "./enum";
export class Storage implements StorageCls {
//存储接受 key value 和过期时间 默认永久
public set<T = any>(key: Key, value: T, expire: expire = Dictionaries.permanent) {
//格式化数据
const data = {
value,
[Dictionaries.expire]: expire
}
//存进去
localStorage.setItem(key, JSON.stringify(data))
}
public get<T = any>(key: Key):Result<T | null> {
const value = localStorage.getItem(key)
//读出来的数据是否有效
if (value) {
const obj: Data<T> = JSON.parse(value)
const now = new Date().getTime()
//有效并且是数组类型 并且过期了 进行删除和提示
if (typeof obj[Dictionaries.expire] == 'number' && obj[Dictionaries.expire] < now) {
this.remove(key)
return {
message:`您的${key}已过期`,
value:null
}
}else{
//否则成功返回
return {
message:"成功读取",
value:obj.value
}
}
} else {
//否则key值无效
console.warn('key值无效')
return {
message:`key值无效`,
value:null
}
}
}
//删除某一项
public remove(key:Key) {
localStorage.removeItem(key)
}
//清空所有值
public clear() {
localStorage.clear()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
然后运行 npm run build就打包成功了。