英文:
Client components in turborepo cause error
问题
我正在尝试在一个单独的内部 UI 包中构建带有 React 客户端组件的 Turborepo。
不幸的是,tsup
删除了位于 ui
包顶部的 use client
指令,而这对于 nextjs 是必需的。错误消息:
> 模块级别的指令在捆绑时会引发错误,"dist/Test.mjs" 中的 "use client" 被忽略了。
最小复现示例,显示了错误:https://shorturl.at/noxzI
有关如何修复此问题的任何提示吗?
EDIT 1:
新的网址:https://rb.gy/gubwk
EDIT 2:
上述最小存储库生成以下错误消息:
> TypeError: a.default.createContext 不是一个函数
根据其他 Stack Overflow 回答,这可能是因为缺少 use client
。如果您在 dist 文件夹中的构建 Test 块中添加 use client
,该错误将消失,并被以下错误替代:
> TypeError: styled_components__WEBPACK_IMPORTED_MODULE_2__.div 不是一个函数
EDIT 3:
只是一个附带的注意事项,无论组件是 js 文件(例如 Test
)还是 tsx 文件(例如 Card
),错误都会发生。不知何故,Webpack 不包括 styled-component 包。
英文:
I am trying to build a Turborepo with react client components in a separate internal ui package.
Unfortunately, tsup
removes the use client
directive at the top of the ui
packages, which are needed for nextjs. Message:
> Module level directives cause errors when bundled, "use client" in
> "dist/Test.mjs" was ignored.
Minimal reproduction sandbox, showing the error: https://shorturl.at/noxzI
Any tips on how to fix this?
EDIT 1:
New URL: https://rb.gy/gubwk
EDIT 2:
The above minimal repo produces the following error message:
> TypeError: a.default.createContext is not a function
Based on other SO answers, that is likely because use client
is missing. If you add use client
to the built Test chunk in the dist folder, that error goes away and is replaced by this error:
> TypeError: styled_components__WEBPACK_IMPORTED_MODULE_2__.div is not
> a function
EDIT 3:
Just a side-note that the error happens regardless of whether the component is a js file (e.g. Test
) or a tsx file (e.g. Card
). Somehow webpack does not include the styled-component
package.
答案1
得分: 3
- 删除 ui 包中的 dist 文件夹。
- 使用以下内容编辑你的 /packages/ui/tsup.config.js 文件:
import { defineConfig, Options } from "tsup";
export default defineConfig((options: Options) => ({
banner: {
js: `"use client"`,
},
// treeshake: true,
splitting: true,
entry: ["./**/*.tsx"],
format: ["esm"],
dts: true,
minify: true,
clean: true,
external: ["react"],
...options,
}));
注意,banner 选项告诉 tsup 不要删除 "use client",我注意到 treeshake 删除了 "太多",所以你可以删除/移除那个选项。使用上述配置,我能够成功构建项目而不产生任何错误。
- 再次运行构建脚本!
英文:
- Delete the dist folder in the ui package.
- Edit your /packages/ui/tsup.config.js file with the following:
import { defineConfig, Options } from "tsup";
export default defineConfig((options: Options) => ({
banner: {
js: `"use client"`,
},
// treeshake: true,
splitting: true,
entry: ["./**/*.tsx"],
format: ["esm"],
dts: true,
minify: true,
clean: true,
external: ["react"],
...options,
}));
Note the banner option telling tsup to not remove the "use client", and I noticed that treeshake was removing "too much" so you can delete/remove that option. With the following config I was able to build the project without any errors.
- run build script again!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论