{"id":17683359,"url":"https://github.com/haixiangyan/my-js-cookie","last_synced_at":"2025-05-12T22:02:12.944Z","repository":{"id":106425312,"uuid":"349915249","full_name":"haixiangyan/my-js-cookie","owner":"haixiangyan","description":"手把手带你造 js-cookie 轮子","archived":false,"fork":false,"pushed_at":"2021-12-15T13:15:43.000Z","size":59,"stargazers_count":20,"open_issues_count":1,"forks_count":1,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-04-20T18:39:51.576Z","etag":null,"topics":["cookie","javascript","js-cookie"],"latest_commit_sha":null,"homepage":"http://yanhaixiang.com/my-js-cookie/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/haixiangyan.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-03-21T06:15:09.000Z","updated_at":"2025-04-18T09:47:33.000Z","dependencies_parsed_at":null,"dependency_job_id":"d0eb8e16-7aa0-475a-b59b-0d42f2c231d4","html_url":"https://github.com/haixiangyan/my-js-cookie","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":"haixiangyan/static-webapp-typescript-template","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/haixiangyan%2Fmy-js-cookie","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/haixiangyan%2Fmy-js-cookie/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/haixiangyan%2Fmy-js-cookie/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/haixiangyan%2Fmy-js-cookie/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/haixiangyan","download_url":"https://codeload.github.com/haixiangyan/my-js-cookie/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253830925,"owners_count":21971001,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cookie","javascript","js-cookie"],"created_at":"2024-10-24T09:45:13.955Z","updated_at":"2025-05-12T22:02:12.877Z","avatar_url":"https://github.com/haixiangyan.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 造一个 js-cookie 轮子\n\n![](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/db9fe0d6cfc249988ce86d0da2e6701c~tplv-k3u1fbpfcp-zoom-1.image)\n\n\u003e 文章源码：https://github.com/Haixiang6123/my-js-cookie\n\u003e\n\u003e 预览链接：http://yanhaixiang.com/my-js-cookie/\n\u003e\n\u003e 参考轮子：https://www.npmjs.com/package/js-cookie\n\nCookie 相信大家都不陌生，但是很多时候我们都是这样：“啊，我这个地方要用 Cookie 了，怎么办？没事，装一个 npm 包嘛”，或者去 MDN 去抄一两个函数。没什么机会手写一个 js-cookie 的库，今天就带大家一起来写一个 js-cookie 的小库。\n\n## 从零开始\n\n首先，我们要摒弃所有所谓的“设计模式”，做一个最 Low 的版本：只有 `get(key)`、`set(key, value)` 和 `del(key)` 3 个 API。\n\n通过对 MDN、菜鸟教程、掘金博客的大量阅读，很快就写出了最简单的 API。\n\n### get\n\n`document.cookie` 长这样：`a=1\u0026b=2`。将 `document.cookie` 字符串转化成 Object，在转化过程中判断是否存在对应的 key，如果有就返回对应的 value 即可。\n\n```ts\nfunction get(key: string): string | null {\n  const cookiePairs = document.cookie ? document.cookie.split('; ') : []\n\n  const cookieStore: Record\u003cstring, string\u003e = {}\n\n  cookiePairs.some(pair =\u003e {\n    const [curtKey, ...curtValues] = pair.split('=')\n\n    cookieStore[curtKey] = curtValues.join('=') // 有可能 value 存在 '='\n\n    return curtKey === key // 如果相等时，就会 break\n  })\n\n  return key ? cookieStore[key] : null\n}\n```\n\n**注意：cookie 的值有可能里会有 '=' 号，所以`split('=')` 后的，还要再 `join('=')` 一下变回原来的值。比如：`a=123=456`，join 后的 value 还是 `123=456`而不是 `123`。**\n\n### set\n\n单纯 set 或 add 一个 cookie 更简单，只需要\n\n```ts\ndocument.cookie = `${key}=${value}`\n```\n\n但其实，一个 cookie 不只有 key 和 value，还有 expires 过期时间以及 path 路径。一个完整的 set 应该长这样。\n\n```ts\ndocument.cookie = `${key}=${value}; expires=${expires}; path=${path}`\n```\n\n当然，我们不希望 set 函数的入参变得很冗余，所以这里的入参设计为：`key`, `value`, `attributes` 3 个。其中，`attributes` 是个对象，里面为 cookie 的属性：expires, path。\n\n```ts\ninterface Attributes {\n  path: string; // Cookie 对应路径\n  expires?: string | number | Date // Cookie 的过期时间，第N天过期\n}\n```\n\n为了提高扩展性，我们再造一个 `defaultAttributes` 作为默认参数传入。\n\n```ts\nconst TWENTY_FOUR_HOURS = 864e5\nconst defaultAttributes: Attributes = {path: '/'}\n\nfunction set(key: string, value: string, attributes = defaultAttributes): string | null {\n  attributes = {...defaultAttributes, ...attributes}\n\n  if (attributes.expires) {\n    // 将过期天数转为 UTC string\n    if (typeof attributes.expires === 'number') {\n      attributes.expires = new Date(Date.now() + attributes.expires * TWENTY_FOUR_HOURS)\n      attributes.expires = attributes.expires.toUTCString()\n    }\n  }\n\n  // 获取 Cookie 其它属性的字符串形式，如 \"; expires=1; path=/\"\n  const attrStr = Object.entries(attributes).reduce((prevStr, attrPair) =\u003e {\n    const [attrKey, attrValue] = attrPair\n\n    if (!attrValue) return prevStr\n\n    prevStr += `; ${attrKey}`\n\n    // attrValue 有可能为 truthy，所以要排除 true 值的情况\n    if (attrValue === true) return prevStr\n\n    // 排除 attrValue 存在 \";\" 号的情况\n    prevStr += `=${attrValue.split('; ')[0]}`\n\n    return prevStr\n  }, '')\n\n  return document.cookie = `${key}=${value}${attrStr}`\n}\n```\n\n上面的操作也非常简单。首先对 expires 做了转成 UTC 时间戳的处理，然后把 `attributes` 拍扁成一个 string，最后追加到 `${key}=${value}` 后面。\n\n**这里可能有人会对这段神秘代号 `864e5` 感兴趣。这是 24 小时的毫秒值，具体可见 [Stackoverflow](https://stackoverflow.com/questions/18359401/javascript-date-gettime-code-snippet-with-mysterious-additional-characters)** 。\n\n### del\n\n删除一个 cookie 一件再简单不过的事了。上面不是已经实现了 `set` 了么，我们把 expires 设置为 -1 天就好了。\n\n```ts\n/**\n * 删除某个 Cookie\n */\nfunction del(key: string, attributes = defaultAttributes) {\n  // 将 expires 减 1 天，Cookie 自动失败\n  set(key, '', {...attributes, expires: -1})\n}\n```\n\n## 编码与解码\n\n虽然没人要求 cookie 要做编码与解码，但是为了更 cookie 不受一些特殊字符的干扰，我们还要需要对 cookie 的值做编码与解码的工作。\n\n这里普及一下：对于 cookie 的行为是有规范，从 [RFC 2109](http://www.ietf.org/rfc/rfc2109.txt) 到 [RFC 2965](http://www.ietf.org/rfc/rfc2965.txt) 再到 [RFC6265](http://www.ietf.org/rfc/rfc6265.txt)。有兴趣的可以看一看。好的，我知道你没有兴趣了。\n\n咳咳，回到代码。这一步需要在 set 里做编码，在 get 里做解码。一般来说，习惯用 encodeURIComponent 和 decodeURIComponent 做编码和解码的工作。\n\n```ts\nfunction get(key: string): string | null {\n  ...\n\n  cookiePairs.some(pair =\u003e {\n    const [curtKey, ...curtValue] = pair.split('=')\n\n    try {\n      // 解码\n      const decodeedValue = decodeURIComponent(curtValue.join('='))  // 有可能 value 存在 '='\n      cookieStore[curtKey] = decodeedValue\n    } catch (e) {}\n\n    return curtKey === key // 如果相等时，就会 break\n  })\n\n  return key ? cookieStore[key] : null\n}\n\nfunction set(key: string, value: string, attributes = defaultAttributes): string | null {\n  ...\n  \n  // 编码\n  value = encodeURIComponent(value)\n\n  ...\n\n  return document.cookie = `${key}=${value}${attrStr}`\n}\n```\n\nso easy ~ 不过，上面的 `encodeURIComponent` 和 `decodeURIComponent` 有点像硬编码一样写在了代码里了，不妨抽象出来用 `defaultConverter` 来封装编码和解码两个操作。\n\n```ts\nexport interface Converter {\n  encode: (text: string) =\u003e string // 编码\n  decode: (text: string) =\u003e string // 解码\n}\n\n// 默认 Cookie 值的转换器\nexport const defaultConverter: Converter = {\n  encode(text: string) {\n    return text.replace(ASCII_HEX_REGEXP, encodeURIComponent)\n  },\n  decode(text: string) {\n    return text.replace(ASCII_HEX_REGEXP, decodeURIComponent)\n  },\n}\n```\n\nset 和 get 函数将会更抽象了。\n\n```ts\nfunction get(key: string): string | null {\n  ...\n      // 解码\n      const decodeedValue = defaultConverter.decode(curtValue.join('='))  // 有可能 value 存在 '='\n  ...\n}\n\nfunction set(key: string, value: string, attributes = defaultAttributes): string | null {\n  ...\n  // 编码\n  value = defaultConverter.encode(value)\n  ...\n}\n```\n\n## 配置中心\n\n上面只是“我们觉得”习惯上会用 `encodeURIComponent` 和 `decodeURIComponent` 来编码和解码。别人可能会用别的编码和解码函数来完成，因此需要提供一个配置中心给开发者。一次配置，以后都会按照初始设置来 `set` 和 `get` 。\n\n像下面的例子，初始时设定 expires 为 1 天，以后直接 `set(xxx, yyy)` 设置 Cookie 过期时间都是 1 天后。\n\n```ts\n// 初始配置\nCookies.atributes = { expires: 1 }\nCookies.converter = {\n  encode(text: string) {\n    return \"hello\"\n  },\n  decode(text: string) {\n    return \"world\"\n  },\n}\n\nCookies.set('aaa', 111) // 过期时间为 1 天，值 aaa=\"hello\"\nCookies.set('bbb', 222) // 过期时间为 1 天，值 bbb=\"hello\"\n\nCookies.get('aaa') // \"world\"\nCookies.get('bbb') // \"world\"\n```\n\n要实现上面的效果，我们需要首先提供一个初始配置中心的入口，然后暴露配置中心。而且还需要将 attributes 和 converter 配置存下来。\n\n```ts\nlet customAttributes: Attributes = defaultAttributes\nlet customConverter: Converter = defaultConverter\n\nfunction get(key: string): string | null {\n  ...\n  const decodedValue = customConverter.decode(curtValue.join('='))  // 有可能 value 存在 '='\n  ...\n}\n\n/**\n * 设置 Cookie key-val 对\n */\nfunction set(key: string, value: string, attributes = defaultAttributes): string | null {\n  attributes = {...customAttributes, ...attributes}\n  \n  ...\n\n  value = customConverter.encode(value)\n  ...\n}\n\n/**\n * 删除某个 Cookie\n */\nfunction del(key: string, attributes = defaultAttributes) {\n  // 将 expires 减 1 天，Cookie 自动失败\n  set(key, '', {...attributes, expires: -1})\n}\n\nconst Cookies = {\n  get,\n  set,\n  del,\n  attributes: customAttributes,\n  converter: customConverter,\n}\n\nexport default Cookies\n```\n\n上面导出了一个函数，每次使用 attributes 的时候都会先和 `customAttributes` 合并，每次编码解码的时候会使用 `customCoverter`。\n\n上面这么实现在使用的时候会很麻烦，每次修改配置就要手动去做合并。\n\n```ts\nCookies.attributes = {...Cookies.attributes, ...{ expires: 2 } }\n```\n\n那我们想：好吧，暴露两个函数做合并呗。\n\n```ts\n...\nfunction withAttributes(myAttributes: Attribute) {\n  customAttributes = {...customAttributes, ...myAttributes}\n}\nfunction withConverter(myConverter: Converter) {\n  customConverter = {...customConverter, ...myConverter}\n}\n\nconst Cookies = {\n  get,\n  set,\n  del,\n  withAttributes,\n  withConverter\n}\n\nexport default Cookies\n```\n\n还有没有问题？有！把 `customAttributes` 和 `customConverter` 放到全局很容易造成污染。想象一下，这个项目很大，有人偷偷把 `customAttributes` 里的 expires 改成 3 天，下个要开发的人可能完全不知情。所以，把这配置项改为局部是十分有必要的。\n\n直接给出实现：\n\n```ts\nfunction init(initConverter: Converter, initAttributes: Attributes) {\n  function get(key: string): string | null {\n    ...\n    const decodeedValue = initConverter.decode(curtValue.join('='))\n    ...\n  }\n\n  function set(key: string, value: string, attributes = customAttributes): string | null {\n    ...\n    attributes = {...initAttributes, ...attributes}\n    value = initConverter.encode(value)\n    ...\n  }\n\n  function del(key: string, attributes = customAttributes) {\n    set(key, '', {...attributes, expires: -1})\n  }\n\n  function withConverter(customConverter: Converter) {\n    return init({...this.converter, ...customConverter}, this.attributes)\n  }\n\n  function withAttributes(customAttributes: Attributes) {\n    return init(this.converter, {...this.attributes, ...customAttributes})\n  }\n\n  return {\n    get,\n    set, \n    del, \n    attributes: initAttributes,\n    converter: initConverter, \n    withAttributes,\n    withConverter\n  }\n}\n\nexport default init(defaultConverter, defaultAttributes)\n```\n\n上面把配置项存放到了生成对象的 `attributes` 和 `converter` 里了。调用 `withConverter`，`withAttributes` 的时候，再次调用 `init` 来创建 Cookies 对象。好处是 withXXX 后是一个全新的对象，不会造成全局污染。\n\n```ts\nconst myCookies = Cookies.withAttributes({ expires: 2 }) // 新对象\n\nattrCookies.set('aaa', 1) // 2 天后过期\n\nCoookies.set('aaa', 1) // 没有过期时间\n```\n\n## 把配置项“冻结”\n\n上面的代码还有个问题，`attributes` 和 `converter` 还是被暴露了出来，万一哪个憨憨手抖改了，后面的接盘侠还是会傻眼。\n\n这里可以用 `Object.create` 来生成对象，并在第 2 个参数里用 `Object.freeze` 把对象 `atributes` 和 `converter`“冻住”。\n\n```ts\nfunction init(initConverter: Converter, initAttributes: Attributes) {\n  ...\n\n  return Object.create(\n    {get, set, del, withConverter, withAttributes},\n    {\n      converter: {value: Object.freeze(initConverter)}, // 被冻动了\n      attributes: {value: Object.freeze(initAttributes)}, // 被冻动了\n    }\n  )\n}\n\nexport default init(defaultConverter, defaultAttributes)\n```\n\n关于 `Object.create` 第 2 个参数的内容可以看 [Object.defineProperties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties)，它的意义是描述对象属性，这里的描述就是“冻动”了。比如：\n\n```ts\nCookies.attributes = 1\n\nconsole.log(Cookies.attributes) // 返回依然是 {path: '/'}，不会变成 1\n```\n\n到此，一个 js-cookie 库已经完美实现了！\n\n## 总结\n\n用 `init` 函数创建对象，对象里有以下函数\n1. get 函数：将 `document.cookie` 字符串转化为 Object 形式，转化过程中判断是否在存 key，如果有就返回对应 value\n2. set 函数：把 `attributes` stringify，然后追加到 key=value 后， `document.cookie = ${key}=${value}${attrStr}`\n3. del 函数：调用 `set`，把 expires 设置为 -1 天，cookie 直接过期被删除\n4. withAttributes：更新 attributes 配置，并返回全新 Cookie 对象\n5. withConverter：更新 converter 配置，并返回全新 Cookie 对象\n\n为什么要用函数生成对象这么麻烦？因为要解决全局污染的问题。需要把 `attributes` 和 `converter` 两个配置存到函数参数里，并且通过 `withAttributes` 和 `withConverter` 调用 `init` 返回新 Cookie 对象。\n\n为什么要冻动 `attributes` 和 `converter`，还是因为怕有憨憨把这两玩意改了。\n\n## 最后\n\n上面的代码其实就是 [js-cookie](https://www.npmjs.com/package/js-cookie) 的核心代码了。\n\n当然这个库里对一些特殊字符处理的代码没有过多提及，因为纠结这些过于细节的代码意义并不大。而且上面已经做了一些特殊字符处理了，已经涵盖大部分使用情况了。\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhaixiangyan%2Fmy-js-cookie","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhaixiangyan%2Fmy-js-cookie","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhaixiangyan%2Fmy-js-cookie/lists"}