jba*_*ann 7 reactjs monorepo react-hooks npm-workspaces turborepo
我一直在设置一个 monorepo,目标是创建一个共享组件库以用于多个不同的 Next.js 应用程序(按照此示例),但是每当我从共享库导入组件时,我都会得到
Unhandled Runtime Error
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
Run Code Online (Sandbox Code Playgroud)
我认为这可能与我在组件中使用的 mui 组件有关,因为该组件可以毫无问题地导入和使用:
// TestComponent.jsx
import * as React from 'react';
export const TestComponent = () => {
return <h1>test</h1>;
};
Run Code Online (Sandbox Code Playgroud)
但这会引发无效的挂钩错误:
// TestButton.jsx
import * as React from 'react';
import { Button } from '@mui/material';
export const TestButton = () => {
return <Button>Boop</Button>;
};
Run Code Online (Sandbox Code Playgroud)
这是我的共享组件包的 package.json:
{
"name": "shared-components",
"version": "0.0.0",
"main": ".dist/index.js",
"module": "./dist/index.mjs",
"sideEffects": false,
"license": "MIT",
"files": [
"dist/**"
],
"scripts": {
"build": "tsup src/index.jsx --format esm,cjs --external react",
"dev": "tsup src/index.jsx --format esm,cjs --watch --external react",
"lint": "TIMING=1 eslint src --fix",
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist"
},
"devDependencies": {
"tsup": "^5.10.1"
},
"peerDependencies": {
"@mui/icons-material": "^5.6.1",
"@mui/material": "^5.6.1",
"@mui/utils": "^5.6.1",
"react": "17.0.2",
"react-dom": "17.0.2"
}
}
Run Code Online (Sandbox Code Playgroud)
我已将其添加到我尝试使用共享组件的项目的 next.config.js 中:
const withTM = require('next-transpile-modules')(['shared-components']);
module.exports = withTM({
reactStrictMode: true,
});
Run Code Online (Sandbox Code Playgroud)
终于解决了这个问题...
我必须将其添加到我的消费者网站的 next.config.js 中
const withTM = require('next-transpile-modules')(['shared-components'], { resolveSymlinks: false });
module.exports = withTM({
reactStrictMode: true,
});
Run Code Online (Sandbox Code Playgroud)
尽管next-transpile-modules 的文档说对于 npm 工作区,resolveSymlinks 默认情况下应保留为 true,但将其设置为 false 是唯一对我有用的方法。
如果有人可以向我澄清为什么这有效,我很乐意了解,但目前它正在按预期工作。
| 归档时间: |
|
| 查看次数: |
1702 次 |
| 最近记录: |