react-tiny-state2: 一个全局状态管理工具

全局状态管理 tree

🕐

安装

pnpm add @jswork/react-tiny-state
pnpm add --dev @jswork/vite-plugin-tiny-state

添加配置

添加配置到 vite.config.ts 中

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import vitePluginTinyState from '@jswork/vite-plugin-tiny-state';

export default defineConfig({
  plugins: [
    react(),
    vitePluginTinyState(), // Zero-config auto-registration
  ],
});

定义业务  store

// src/stores/counter.ts
import nx from '@jswork/next';

export default nx.$defineStore({
  state: { count: 0 },
  getters: { double: (state) => state.count * 2 },
  actions: {
    increment: (state) => nx.$set('counter.count', state.count + 1),
  },
});

嵌套类型

// src/stores/member/profile.ts -> module name: memberProfile
export default nx.$defineStore({
  state: { nickname: 'Alice' },
});

直接在组件中使用

function Counter() {
  const count = nx.$use('counter.count');
  return <button onClick={() => nx.$call('counter.increment')}>{count}</button>;
}

更多插件配置

vitePluginTinyState({
  /**
   * Glob pattern to scan store modules.
   * @default '/src/stores/**\/*.ts'
   */
  pattern?: string;

  /**
   * Automatically inject virtual module import into the entry file.
   * @default true
   */
  autoInject?: boolean;

  /**
   * Target entry file path to inject.
   * @default 'src/main.tsx'
   */
  entry?: string;
});