使用@mui创建reactjs Web组件库时出错

问题描述 投票:0回答:2

我想用来自 @mui

的个性化组件创建一个 ReactJS 库

没有这样的组件它工作正常,但是当我从中添加任何内容时,出现以下错误:

index.js:647 Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this 
Uncaught TypeError: Cannot read properties of null (reading 'useContext')
    at Object.useContext (index.js:2011:1)
    at useTheme$3 (index.js:11650:1)
    at ThemeProvider$1 (index.js:11690:1)
    at renderWithHooks (react-dom.development.js:16316:1)
    at mountIndeterminateComponent (react-dom.development.js:19986:1)
    at beginWork (react-dom.development.js:21454:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4112:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4161:1)
    at invokeGuardedCallback (react-dom.development.js:4223:1)
    at beginWork$1 (react-dom.development.js:27241:1)

我似乎遇到了第 3 种情况,“同一个应用程序中存在多个 React 副本”,但我不知道如何解决它,有办法在我的 React 组件中使用像 @mui 这样的库吗?

这是我的汇总配置:

import peerDepsExternal from "rollup-plugin-peer-deps-external"
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "@rollup/plugin-typescript";
import postcss from "rollup-plugin-postcss";
import image from "@rollup/plugin-image";
import dts from "rollup-plugin-dts";

const packageJson = require("./package.json");

export default [
    {
        input: "src/index.ts",
        output: [
            {
                file: packageJson.main,
                format: "cjs",
                sourcemap: true,
            },
            {
                file: packageJson.module,
                format: "esm",
                sourcemap: true,
            },
        ],
        plugins: [
            peerDepsExternal(),
            resolve(),
            commonjs(),
            typescript({tsconfig: "./tsconfig.json"}),
            image(),
            postcss(),
        ],
    },
    {
        input: "dist/esm/types/index.d.ts",
        output: [{file: "dist/index.d.ts", format: "esm"}],
        plugins: [dts()],
        external: [/\.css$/],
    },
];

reactjs material-ui web-component rollup
2个回答
3
投票

找到了!我将其留在这里供参考...

您在两个项目(库和使用者)中可能拥有的所有依赖项都需要作为 peedDependecies 添加到您的库中

package.json

"dependencies": {
// moved from here
 }
"peerDependencies": {
// to here
    "react": "^18.2.0",
    "@emotion/react": "^11.9.3",
    "@emotion/styled": "^11.9.3",
    "@mui/icons-material": "^5.8.4",
    "@mui/material": "^5.0.0"
  },

在您的消费者应用程序中

package.json
请务必添加相同的依赖项和版本。


0
投票

不适合我,我尝试了一切

© www.soinside.com 2019 - 2024. All rights reserved.