Next.js 13 App目录下Bootstrap JS导入位置及功能异常排查
Next.js 13 App目录下Bootstrap下拉交互失效与「document not defined」问题解决
问题根源
- Next.js 13 App目录的组件默认是服务器组件,服务器端渲染时不存在浏览器的
document对象,直接导入依赖浏览器环境的Bootstrap JS就会抛出「document not defined」错误。 - 下拉组件仅样式生效、交互失效,是因为Bootstrap的JS逻辑未在浏览器端正确加载执行。
解决方案
方法一:动态导入客户端组件(推荐)
通过单独的客户端组件加载Bootstrap JS,避免服务器端执行浏览器环境代码:
- 创建
BootstrapClient.tsx客户端组件:
'use client'; import 'bootstrap/dist/js/bootstrap.min.js'; export default function BootstrapClient() { return null; // 仅用于加载Bootstrap JS,无需渲染内容 }
- 在
RootLayout.tsx中引入该组件:
import './globals.css'; import './styles/index.scss'; import BootstrapClient from './BootstrapClient'; export const metadata = { title: 'Create Next App', description: 'Generated by create next app', }; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang='en'> <body> <BootstrapClient /> {children} </body> </html> ); }
方法二:将根布局改为客户端组件
直接给RootLayout添加客户端指令,让Bootstrap JS在浏览器环境加载:
'use client'; import 'bootstrap/dist/js/bootstrap.min.js'; import './globals.css'; import './styles/index.scss'; export const metadata = { title: 'Create Next App', description: 'Generated by create next app', }; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang='en'> <body>{children}</body> </html> ); }
注意:此方法会让根布局失去服务器组件的性能优势,仅适合小型项目或快速测试。
方法三:使用next/script加载CDN脚本
利用Next.js的Script组件在浏览器端异步加载Bootstrap:
import './globals.css'; import './styles/index.scss'; import Script from 'next/script'; export const metadata = { title: 'Create Next App', description: 'Generated by create next app', }; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang='en'> <body> {children} <Script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" strategy="afterInteractive" /> </body> </html> ); }
strategy="afterInteractive"确保脚本在页面可交互后加载,不影响首屏渲染速度。
内容的提问来源于stack exchange,提问作者Bhavesh Kumar Sharma
相关产品推荐
相关产品推荐

