【问题标题】:How to properly bundle material ui with a react component npm package如何将材料 ui 与反应组件 npm 包正确捆绑
【发布时间】:2020-12-27 00:09:21
【问题描述】:

我在将材料 ui 与我的 react 组件包捆绑时遇到问题。捆绑后出现的错误是这样的。

× 错误:无效的挂钩调用。 Hooks 只能在内部调用 功能组件的主体。这可能发生在其中一个 原因如下:

这是简单的组件,

import React, { Fragment } from "react";
import TextField from "@material-ui/core/TextField";
import Typography from "@material-ui/core/Typography";
import { createMuiTheme, ThemeProvider } from "@material-ui/core/styles";
import InputAdornment from "@material-ui/core/InputAdornment";
import GifIcon from "@material-ui/icons/Gif";
import { Grid } from "@material-ui/core";
type CommentType = {
  style?: object;
};
const theme = createMuiTheme({
  palette: {
    primary: {
      main: "#48A9A6",
    },
    secondary: {
      main: "#000000",
    },
  },
});

class CommentBox extends React.Component {
  render() {
    return (
      <Fragment>
        <Grid>Owls are cool</Grid>
      </Fragment>
    );
  }
}
export default CommentBox;

这是调用它的地方(在另一个项目中)

App.js

import React from "react";
import logo from "./logo.svg";
import "./App.css";
import CommentBox from "commentbox-simple-demo";
function App() {
  return (
    <div className="App">
      <CommentBox />
    </div>
  );
}

export default App;

仅当我在组件中使用材质 ui 组件时才会发生此错误。网格、排版等组件。

我做错了什么?

webpack.config.js

const path = require("path");

module.exports = {
  mode: "development",
  entry: "./src/index.ts",
  output: {
    filename: "index.js",
    path: path.join(__dirname, "dist"),
    libraryTarget: "commonjs2",
  },

  module: {
    rules: [
      {
        test: /\.ts|tsx|js?$/,
        exclude: /node_modules/,
        use: ["ts-loader"],
      },
    ],
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".jsx"],
  },
};

tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "esModuleInterop": true,
    "module": "esnext",
    "target": "es6",
    "moduleResolution": "node",
    "jsx": "react",
    "declaration": true
  }
}

【问题讨论】:

  • 你检查了错误信息中提到的所有点吗?
  • 是的。我不知道为什么使用材质 ui 在使用组件时会引发错误。
  • index.js:1 Fetch API cannot load webpack:///./node_modules/react/cjs/react.development.js?. URL scheme must be "http" or "https" for CORS request 这意味着什么?
  • 兄弟,用create-react-app ????
  • 我不明白你的意思?这是一个 npm 包,我在捆绑 react 包组件时不能使用 create-react-app。

标签: reactjs webpack material-ui


【解决方案1】:

修复它,我必须从我的包组件中删除 reactreact-dom,然后在演示应用上重新安装包。所以我想为了避免无效的钩子错误,我需要从我的包组件中删除reactreact-dom 文件夹,然后尝试重新安装

这个教程很有帮助

https://juliangaramendy.dev/react-typescript-library-tsdx/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 2020-12-20
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多