You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Mantine的内部npm组件库useContext错误的解决疑问

问题解决方案

这个错误的核心原因是组件库中的Mantine上下文与使用项目的Mantine上下文不是同一个实例——大概率是你打包组件库时,把@mantine/core、@mantine/hooks等Mantine依赖一起打包进了产物,导致组件库用的是自身包里的上下文,而项目中的MantineProvider是基于项目安装的Mantine实例,两者无法匹配。

以下是具体修复步骤:

1. 调整组件库的依赖配置

将Mantine相关依赖移到peerDependencies中,避免组件库打包这些依赖,直接复用项目中安装的Mantine版本:

// 组件库的package.json
{
  "peerDependencies": {
    "@mantine/core": "^6.0.0", // 匹配你使用的Mantine版本
    "@mantine/hooks": "^6.0.0",
    "react": "^18.0.0",
    "react-dom": "^18.0.0"
  },
  "devDependencies": {
    "@mantine/core": "^6.0.0",
    "@mantine/hooks": "^6.0.0",
    // 其他开发依赖(如打包工具、TypeScript等)
  }
}

2. 配置打包工具排除Mantine依赖

确保打包时不把peerDependencies中的依赖打包进组件库产物:

  • 若用Rollup,在配置中添加external:
    export default {
      external: ['react', 'react-dom', '@mantine/core', '@mantine/hooks'],
      // 其他打包配置
    }
    
  • 若用Vite打包库,修改vite.config.ts:
    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    
    export default defineConfig({
      plugins: [react()],
      build: {
        lib: {
          entry: 'src/index.ts',
          name: 'YourComponentLibrary',
          fileName: (format) => `your-library.${format}.js`,
        },
        rollupOptions: {
          external: ['react', 'react-dom', '@mantine/core', '@mantine/hooks'],
          output: {
            globals: {
              react: 'React',
              'react-dom': 'ReactDOM',
              '@mantine/core': '@mantine/core',
              '@mantine/hooks': '@mantine/hooks',
            },
          },
        },
      },
    });
    

3. 重新发布并验证

  • 重新打包组件库,更新版本后发布到npm。
  • 在使用项目中,确保已安装匹配版本的Mantine依赖,且在应用最外层用MantineProvider包裹(比如src/main.tsx):
    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import { MantineProvider } from '@mantine/core';
    import App from './App';
    
    ReactDOM.createRoot(document.getElementById('root')!).render(
      <React.StrictMode>
        <MantineProvider>
          <App />
        </MantineProvider>
      </React.StrictMode>
    );
    

额外排查:如果项目中存在多个MantineProvider嵌套,确保组件库的组件在正确的Provider范围内渲染,不要在Provider之外使用组件。

内容的提问来源于stack exchange,提问作者Haseeb Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 06:58:24