Skip to content

前端生成唯一

使用场景

  • 短链生成
  • 唯一标识
  • 唯一 ID 生成

使用示例

npm 安装

bash
npm install nanoid
  • 导入依赖
bash
import { nanoid } from 'nanoid'

CDN 安装

  • nanoid不支持 script 导入,需要使用 es6 模块
html
<script type="module">
  import { nanoid } from "https://cdn.jsdelivr.net/npm/nanoid@5.1.6/+esm";
</script>

使用方法

第一种

html
<script type="module">
  import { nanoid } from "https://cdn.jsdelivr.net/npm/nanoid@5.1.6/+esm";
  const id = nanoid();
  console.log(id); // 7K5uJ_khAInvgTCaDS9U9
</script>

第二种 自定义生成内容

html
<script type="module">
  import { customAlphabet } from "https://cdn.jsdelivr.net/npm/nanoid@5.1.6/+esm";
  // 自定义生成内容,并且只生成 4位 验证码
  const nanoid = customAlphabet("1234567890abcdef", 4);
  const id = nanoid();
  console.log(id); // f513
</script>