在 typescript 中生成 uuid 的方法:直接使用 uuid 庫(uuid 或 uuid-JS)使用 node.js 中的 crypto.randomuuid() 方法使用 v4 方法(rfc 4122 版本 4 uuid)自定義實現(遵循 rfc 4122 規范)最佳方法取決于具體情況:庫易用,crypto.randomuuid() 快速,v4 方法標準,自定義實現可定制。
如何在 typescript 中生成 UUID
直接使用 UUID 庫
提供 UUID 生成功能的 TypeScript 庫包括:
- uuid:適用于 Node.js 和瀏覽器。
- uuid-js:適用于瀏覽器。
通過 crypto.randomUUID()
在 Node.js 中,可以使用 crypto.randomUUID() 方法生成 UUID:
import {randomUUID} from 'crypto'; const uuid = randomUUID();
登錄后復制
使用 v4 方法
v4 是一個 RFC 4122 版本 4 UUID 的實現。
import {v4 as uuidV4} from 'uuid'; const uuid = uuidV4();
登錄后復制
自定義實現
可以實現自己的 UUID 生成器,遵循 RFC 4122 規范:
function generateUUID(): string { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { const r = Math.random() * 16 | 0; const v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); }
登錄后復制
選擇最佳方法
選擇生成 UUID 的最佳方法取決于具體情況:
- 庫:易于使用,提供各種功能。
- crypto.randomUUID():適用于 Node.js,快速且可靠。
- v4 方法:RFC 4122 版本 4 UUID 的標準實現。
- 自定義實現:可定制,但需要理解 UUID 規范。