dwj*_*ton 10 reactjs material-ui lerna react-context
我正在使用 lerna 创建一个 monorepo,其中我有一个这样的结构:
root
packages
application - Our root application
components - Just some react components, that are to be used by the application
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是我正在使用 Material-UI 及其主题功能,在应用程序根目录中,我们将有一个 ThemeProvider:
import { ThemeProvider } from '@material-ui/styles';
//...
function App() {
return (
<ThemeProvider theme={theme}>
<MyMaterialComponent/>
</ThemeProvider>
);
}
Run Code Online (Sandbox Code Playgroud)
然后在库组件中,我们使用主题,在我们的例子中使用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>
);
}
Run Code Online (Sandbox Code Playgroud)
现在这一切似乎都很简单。当我们在同一个包中运行此代码时,它工作正常。该样式功能可以访问主题。
但是当我从另一个包(我们的应用程序包)运行时,组件库不再可以访问主题(主题只是一个空对象)。
我目前知道如何解决这个问题的唯一方法与我解决类似钩子问题的方法相同,即在我的应用程序中设置 webpack 别名配置,以指示组件库共享相同的节点模块。(请参阅此 Github 线程和建议的解决方案)。
IE。使用 react-app-rewired 和 custom-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")
})
)
Run Code Online (Sandbox Code Playgroud)
或者你可以手动管理你的 webpack 来做类似的事情。
所以这工作正常,但这不是一个特别令人满意的解决方案。
特别是对于像 Material-UI 这样的库,您希望用户能够使用您的组件库,而无需他们弄乱他们的 webpack 配置。
所以我想我一定在这里做错了 - 你能告诉我什么吗?
您可以通过将@material-ui/core依赖项从 devDependency 放置到库项目中的 peerDependency 来实现此目的。就我而言,这解决了我的问题。
有关对等依赖性的更多信息:
https://classic.yarnpkg.com/en/docs/dependency-types/#toc-peerdependency
| 归档时间: |
|
| 查看次数: |
1174 次 |
| 最近记录: |