You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS集成Fomantic UI遇「Cannot read properties...」服务端错误求助

解决NextJS集成Fomantic UI时的「Cannot read properties of undefined (reading 'prototype')」服务端错误

问题原因

semantic-ui-react 依赖 jQuery,但 NextJS 服务端渲染环境中不存在浏览器的 window 对象,jQuery 初始化时会因无法访问相关属性抛出错误,仅在使用该库的页面触发。

解决方案步骤

  1. 安装依赖的 jQuery
    执行命令补充安装 jQuery:

    npm install jquery
    
  2. 配置 NextJS 的 webpack 全局注入 jQuery
    在项目根目录的 next.config.js(没有则新建)中添加以下配置:

    const webpack = require('webpack')
    
    module.exports = {
      webpack: (config) => {
        config.plugins.push(
          new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery'
          })
        )
        return config
      }
    }
    
  3. 正确导入 CSS 和组件
    推荐在全局的 pages/_app.js 中导入 Fomantic UI 的 CSS,避免单个页面导入引发的服务端问题:

    // pages/_app.js
    import 'fomantic-ui-css/semantic.min.css'
    import '../styles/globals.css' // 保留你原有的全局 CSS
    
    function MyApp({ Component, pageProps }) {
      return <Component {...pageProps} />
    }
    
    export default MyApp
    

    之后页面组件只需正常导入组件即可:

    import { Button } from 'semantic-ui-react'
    
    export default function Page() {
      return (
        <Button primary>Click Here</Button>
      )
    }
    

    如果仅需在单个页面使用,也可以用动态导入禁用服务端渲染:

    import dynamic from 'next/dynamic'
    import { useEffect } from 'react'
    
    // 动态导入 Button 并禁用 SSR
    const Button = dynamic(() => import('semantic-ui-react').then(mod => mod.Button), {
      ssr: false
    })
    
    export default function Page() {
      // 在客户端加载 CSS
      useEffect(() => {
        import('fomantic-ui-css/semantic.min.css')
      }, [])
    
      return (
        <Button primary>Click Here</Button>
      )
    }
    

内容的提问来源于stack exchange,提问作者user2114189

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 00:27:05