localStorage

一个修改版的 Storybook 附加组件,允许你模拟 `localStorage` 数据

在 Github 上查看

Storybook LocalStorage 附加组件

一个用于模拟和显示 window.localStorage 在 Storybook 面板中的当前值的 Storybook v8 附加组件和装饰器

如果你想设置强类型的 `parameters`,请查看 @alexgorbatchev/storybook-parameters

安装

npm i --save-dev @alexgorbatchev/storybook-addon-localstorage

在 `./storybook/main.js` 中注册附加组件

export default {
  stories: ['../stories/**/*.stories.tsx'],
  addons: ['@alexgorbatchev/storybook-addon-localstorage'],
};

重要

  • 如果设置了 `parameters.localStorage`,则会在填充值之前调用 `localStorage.clear()`。
  • 传递给 `parameters.localStorage` 的值 **必须是字符串**,因为 `localStorage` 只能处理字符串。你可以使用 `JSON.stringify`,或者使用附加组件提供的名为 `localStorageForStorybook` 的辅助函数。
  • 最后,重要的是要注意,附加组件通过每 100 毫秒轮询和对比 `localStorage` 中模拟的值来工作。

使用

给定一个简单的组件

export const Header = () => {
  const [user, setUser, { removeItem }] = useLocalStorage<{ name: string }>('user');

  return (
    <div>
      {user ? (
        <div>
          <div>{`Logged in as ${user.name}`}</div>
          <Button size="small" label="Log out" onClick={() => removeItem()} />
        </div>
      ) : (
        <div>
          <div>No one is signed in</div>
          <Button size="small" label="Log in" onClick={() => setUser({ name: 'John' })} />
        </div>
      )}
    </div>
  );
};

你可以这样写一个故事

import { localStorageForStorybook } from '@alexgorbatchev/storybook-addon-localstorage';
import { Meta, StoryObj } from '@storybook/react';

import { Header } from './Header';

const meta: Meta<typeof Header> = {
  title: 'Example/Header',
  component: Header,
};

export default meta;

type Story = StoryObj<typeof Header>;

export const JohnLoggedIn: Story = {
  parameters: {
    // this helper automatically stringifies the values using `JSON.stringify`
    localStorage: localStorageForStorybook({
      value: 123,
      user: { name: 'John' },
    }),
  },
};

export const JaneLoggedIn: Story = {
  parameters: {
    // if you have own serialzer, you can use it as well
    localStorage: {
      value: '123',
      user: JSON.stringify({ name: 'Jane' }),
    },
  },
};

强类型示例

import { Meta, StoryObj } from '@alexgorbatchev/storybook-parameters';
import { LocalStorageParameters } from '@alexgorbatchev/storybook-addon-localstorage';

interface StoryParameters extends LocalStorageParameters {}

const meta: Meta<typeof Header, StoryParameters> = {
  title: 'Header',
  component: Header,
};

export default meta;

type Story = StoryObj<typeof Header, StoryParameters>;

export const JohnLoggedIn: Story = {
  parameters: {
    // `localStorage` will show up in `Parameters`
    localStorage: {
      key: 'value',
    },
  },
};

开发脚本

  • npm run storybook 启动 Storybook
  • tsup 构建 ./dist