【问题标题】:How do I share context between a library component, and my application component?如何在库组件和我的应用程序组件之间共享上下文?
【发布时间】:2019-10-13 17:55:35
【问题描述】:

我正在使用 lerna 创建一个 monorepo,我的结构如下:

root 
  packages
    application - Our root application 
    components  - Just some react components, that are to be used by the application

这里是a working Github with a simple example for this

我遇到的问题是,我正在使用 Material-UI 及其主题功能,在应用程序根目录中我们将有一个 ThemeProvider:

import { ThemeProvider } from '@material-ui/styles';
//...

function App() {
  return (

  <ThemeProvider theme={theme}>
          <MyMaterialComponent/>
  </ThemeProvider>
  );
}

稍后在库组件中,我们使用主题,在我们的例子中使用makeStyles 钩子。

import React from 'react';
import { makeStyles } from '@material-ui/styles';
import Card from "@material-ui/core/Card";

const useStyles = makeStyles(theme => {
    console.log(theme); //When this component doesn't have access to the theme, this is `{}`
    return {
        root: {
            //color: theme.palette.primary.main  //will error
        }
    }
});

export function MyMaterialComponent({ }) {
    const classes = useStyles();
    return (<Card>
            <span className={classes.root}>This is some component</span>
        </Card>
    );

}

现在这看起来很简单。当我们在同一个包中运行此代码时,它工作正常。该样式功能可以访问主题。

但是当我从另一个包(我们的应用程序包)运行时,组件库不再有权访问主题(主题只是一个空对象)。

我目前知道如何解决这个问题的唯一方法,与我解决类似钩子问题的方法相同,即在我的应用程序中设置 webpack 别名配置,以指示组件库共享同一个节点模块。 (See this Github thread and the suggested solution)。

即。使用 react-app-rewired 和 customize-cra 我有一个 config-overrides.js 看起来像这样:

const {
    override,
    addWebpackAlias,
  } = require("customize-cra");

const path = require('path'); 

module.exports = override( 
    addWebpackAlias({
        react: path.resolve('./node_modules/react'), 
        //comment out the line below to reproduce the issue
        "@material-ui/styles": path.resolve("./node_modules/@material-ui/styles") 
    })
)

或者你可以手动管理你的 webpack 来做类似的事情。

所以这很好用,但这不是一个特别令人满意的解决方案。

特别是对于像 Material-UI 这样的库,您希望用户能够使用您的组件库,而不会让他们弄乱他们的 webpack 配置。

所以我想我一定是在这里做错了——你能告诉我什么吗?

【问题讨论】:

  • 好的,这可能只是在通过 lerna 符号链接使用库时才是更大的问题,如果库发布到 npm,那就没问题了。谁能确认一下?
  • 你找到这个了吗?我现在和你碰壁了。
  • @Hespen - 我正在使用我在这里概述的解决方案,但是,它并不理想,我必须寻找更好的解决方案。我打算这样做的方法是看看其他开源库在做什么。

标签: reactjs material-ui react-context lerna


【解决方案1】:

您可以通过将您的 @material-ui/core 依赖项从 devDependencies 放置到您的库项目中的 peerDependencies 来实现。就我而言,这解决了我的问题。

有关 peerDependencies 的更多信息:

https://classic.yarnpkg.com/en/docs/dependency-types/#toc-peerdependencies

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多