
本文档旨在解决在使用 Mantine UI 构建可复用组件库并在其他项目中引入时,遇到的 TypeError: Cannot read properties of null (reading 'useContext') 错误。该错误通常与模块编译方式有关。通过修改 TypeScript 配置文件,将 CommonJS 编译方式改为 ESM,可以有效解决此问题,并确保组件库的正常使用。
在使用 Mantine UI 作为基础,构建自己的组件库并发布到 npm 后,在另一个 React 项目中使用该组件库时,可能会遇到以下错误:
TypeError: Cannot read properties of null (reading 'useContext')
这个错误通常表明 Mantine UI 相关的 Context 在组件树中没有正确提供。尽管你在使用组件库的项目中已经包裹了 MantineProvider,但问题依然存在。
根本原因在于组件库的编译方式。如果你的组件库使用 TypeScript 编译为 CommonJS (CJS) 模块,则可能会导致在使用组件库的项目中,Mantine UI 的 Context 无法正确传递。这是因为 CJS 和 ESM 模块在处理依赖关系的方式上有所不同,可能导致 Context 丢失。
解决此问题的关键是将组件库编译为 ECMAScript 模块 (ESM)。这可以通过修改组件库的 tsconfig.json 文件来实现。
打开组件库的 tsconfig.json 文件,并进行如下修改:
{
"exclude": ["node_modules"],
"include": ["src"],
"compilerOptions": {
"module": "ES2020", // 将 module 设置为 ESM 相关的值,例如 "ES2020", "ESNext"
"declaration": true,
"outDir": "dist/esm",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"removeComments": true,
"strict": true,
"skipLibCheck": true,
"jsx": "react",
"moduleResolution": "node",
"lib": ["dom", "es2016", "esnext.asynciterable"],
"sourceMap": true,
"declarationDir": "dist/types"
}
}关键配置项解释:
在修改 tsconfig.json 后,重新编译组件库。确保编译输出目录(例如 dist/esm)包含 ESM 格式的模块文件。
将重新编译后的组件库发布到 npm。
在使用组件库的项目中,更新组件库的依赖,并确保安装的是最新版本。
以下是一个简单的 Mantine UI 组件示例,用于验证解决方案:
import React from "react";
import { Button as MantineButton } from "@mantine/core";
import PropTypes from "prop-types";
const ButtonTest = ({ label, backgroundColor = "red", handleClick }) => {
const style = {
backgroundColor,
border: "none",
padding: "10px",
};
return (
<div>
<MantineButton onClick={handleClick} style={style}>
{label}
</MantineButton>
</div>
);
};
ButtonTest.propTypes = {
label: PropTypes.string,
backgroundColor: PropTypes.string,
handleClick: PropTypes.func,
};
export default ButtonTest;确保在使用此组件的项目中,已经正确引入并使用了 MantineProvider。
通过将组件库编译为 ESM 模块,可以有效解决在使用 Mantine UI 构建组件库时遇到的 useContext 报错问题。这种方法确保了 Mantine UI 的 Context 在组件树中正确传递,从而保证了组件库的正常运行。 记住,在修改配置后,一定要重新编译、发布并更新依赖。
以上就是基于 Mantine UI 构建组件库时 useContext 报错的解决方案的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号