本文档旨在解决在使用 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 丢失。
解决方案:将组件库编译为 ESM
解决此问题的关键是将组件库编译为 ECMAScript 模块 (ESM)。这可以通过修改组件库的 tsconfig.json 文件来实现。
修改 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" } }
关键配置项解释:
- module: 将其设置为 “ES2020” 或 “ESNext”,指定 TypeScript 编译器生成 ESM 模块。
- outDir: 指定 ESM 模块的输出目录,例如 “dist/esm”。
- esModuleInterop: 设置为 true,允许 CommonJS 模块和 ES 模块之间的互操作。
重新编译组件库
在修改 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。
注意事项
- 确保你的 TypeScript 版本是最新的,以支持最新的 ESM 特性。
- 在更新组件库依赖后,清除 node_modules 目录并重新安装依赖,以避免缓存问题。
- 检查构建工具(例如 webpack, rollup)的配置,确保它们正确处理 ESM 模块。
总结
通过将组件库编译为 ESM 模块,可以有效解决在使用 Mantine UI 构建组件库时遇到的 useContext 报错问题。这种方法确保了 Mantine UI 的 Context 在组件树中正确传递,从而保证了组件库的正常运行。 记住,在修改配置后,一定要重新编译、发布并更新依赖。
react js json node typescript 工具 red typescript json ecmascript npm webpack NULL 并发 ui