TS 封装 LocalStorage
LocalStorage 模仿 cookie 实现设置过期时间的库。
项目文件结构
- src
- enum
index.ts (存放枚举)
- type
index.ts (存放类型)
index.ts (实现代码逻辑)
- index.html (代码测试)
- package.json
- rollup.config.js
- tsconfig.json
修改 tsconfig.json
"compilerOptions": { "module": "ESNext", "moduleResolution": "node", "strict": false }
具体实现
enum/index.ts
export enum Dictionaries{
permanent = 'permanent'; // 默认是永久的(永不过期)
expire = '__expire__'; // 过期时间
}
type/index.ts
import { Dictionaries } from "../enum";
export type Key = string;
export type Expire = Dictionaries.permanent | number; // 过期时间为永久或一个时间戳
export interface Result<T> {
message: string;
value: T | null;
}
export interface Data<T> {
value: T;
[Dictionaries.expire]: Expire;
}
export interface StorageCls {
get: <T>(key: Key) => void;
set: <T>(key: Key, value: T, expire: Expire) => void;
remove: (key: Key) => void;
clear: () => void;
}
index.ts
import { StorageCls, Key, Expire, Data, Result } from "./type";
import { Dictionaries } from "./enum";
export class Storage implements StorageCls {
set<T>(key: Key, value: T, expire: Expire = Dictionaries.permanent) {
const data = {
value, // 用户的value
[Dictionaries.expire]: expire, // 过期时间
};
localStorage.setItem(key, JSON.stringify(data));
}
get<T>(key: Key): Result<T | null> {
const value = localStorage.getItem(key);
if (value) {
const data: Data<T> = JSON.parse(value);
const now = new Date().getTime();
// 判断是否过期
if (
typeof data[Dictionaries.expire] == "number" &&
data[Dictionaries.expire] < now
) {
this.remove(key);
return {
message: `您的${key}已过期`,
value: null,
};
} else {
return {
message: "成功",
value: data.value,
};
}
} else {
return {
message: "值无效",
value: null,
};
}
}
remove(key: Key) {
localStorage.removeItem(key);
}
clear() {
localStorage.clear();
}
}
打包配置
使用 rollup 进行打包:
npm install rollup typescript rollup-plugin-typescript2
rollup.config.js
import ts from "rollup-plugin-typescript2";
import path from "path";
export default {
input: "./src/index.ts",
output: {
file: path.resolve(__dirname, "./dist/index.js"),
},
plugins: [ts()],
};
新版 rollup 的打包方法:
import ts from "rollup-plugin-typescript2"; import path from "path"; 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()], };还需要在 package.json 里
type="module"。
启动命令
rollup -c
测试使用
index.html
...
<body>
<script type="module">
import {Storage} from './dist/index.js';
const ls = new Storage()
ls.set('a', 123. new Date().getTime() + 5000);
console.log(les.get('a'));
</script>
</body>