错误:此模块无法从服务器组件模块中导入。它只能从客户端组件中使用。
Error: This module cannot be imported from a Server Component module. It should only be used from a Client Component.
ID: nextjs/server-component-import-client-side-only-module
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Next.js 13.4.0 | active | — | — | — |
| Next.js 14.0.0 | active | — | — | — |
| Next.js 14.2.0 | active | — | — | — |
根因分析
一个使用浏览器专用 API(如 window, document)或在模块级别标记了 'use client' 的模块被导入到服务器组件中,而服务器组件在服务器上运行,这些 API 不存在。
English
A module that uses browser-only APIs (e.g., window, document) or is marked with 'use client' at the module level is imported into a Server Component, which runs on the server where those APIs don't exist.
官方文档
https://nextjs.org/docs/app/building-your-application/rendering/server-components#third-party-packages解决方案
-
Use dynamic import with ssr: false to load the module only on the client: 'const MyComponent = dynamic(() => import('./MyClientComponent'), { ssr: false })'. -
Create a wrapper Client Component that imports the module and pass props from the Server Component.
-
If the module is small, refactor it to avoid browser APIs and make it usable on the server.
无效尝试
常见但无效的做法:
-
60% 失败
This converts the entire Server Component to a Client Component, losing server-side benefits and potentially causing other issues.
-
70% 失败
The module may still use browser APIs internally; removing the directive doesn't make the code run on the server.
-
80% 失败
Dynamic import alone still runs on the server during SSR; use ssr: false to disable server-side rendering.