使用Vite+TypeScript时Zustand报Missing "./react" export错误求助
解决Zustand报错
Missing "./react" export in "zustand" package 问题根源
Zustand v4及以上版本调整了包的导出结构,不再默认提供React相关API的顶层导出,必须显式指定zustand/react路径导入。
可行解决方案
1. 修正导入路径(推荐)
如果使用Zustand v4+,修改store的导入语句:
错误导入:
import { create } from 'zustand'
改为正确导入:
import { create } from 'zustand/react'
确保你的useBearStore是通过这个修正后的create方法创建的。
2. 降级至Zustand v3(可选)
若不想调整导入逻辑,可降级到v3版本:
npm install zustand@3.x # 或使用yarn yarn add zustand@3.x
降级后可继续使用原有的顶层导入方式。
3. 清除依赖缓存重装
若上述方法无效,大概率是依赖缓存问题:
- 删除
node_modules文件夹 - 删除
package-lock.json或yarn.lock文件 - 重新安装依赖:
npm install # 或 yarn install
- 重启Vite开发服务器
验证用完整示例
修正导入后的store代码:
// src/store/bearStore.ts import { create } from 'zustand/react' interface BearStore { bears: number increase: () => void } export const useBearStore = create<BearStore>((set) => ({ bears: 0, increase: () => set((state) => ({ bears: state.bears + 1 })), }))
组件中使用(注意补充状态依赖):
import { useBearStore } from '@/store/bearStore' import { useEffect } from 'react' function BearCounter() { const bears = useBearStore((state) => state.bears) useEffect(() => { console.log(bears) }, [bears]) return <div>Number of bears: {bears}</div> } export default BearCounter
内容的提问来源于stack exchange,提问作者Jordan Baron
相关产品推荐
相关产品推荐

