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

使用Shadcn库时Next.js提示cn不是函数的问题求助

解决Next.js中Shadcn组件的cn函数导入问题

问题分析

你遇到的cn is not a function错误,核心原因是导入路径不匹配或模块导出/导入语法不对应。结合你的代码,以下是针对性的解决步骤:


解决方案

1. 确认文件结构,使用相对路径导入(最直接的解决方式)

假设你的项目文件结构如下:

project-root/
  ├── utils/
  │   └── cn.js  # 你的cn函数文件
  └── components/
      └── Separator.js  # 你的Separator组件

在Separator.js中使用相对路径导入cn函数,避免根路径解析的配置问题:

// Separator.js
import { cn } from '../utils/cn' // 根据实际层级调整路径,比如components/ui/Separator.js则用../../utils/cn

2. 配置根路径导入(适合大型项目)

如果想使用@/utils/cn这类简洁的根路径,需要在项目根目录的jsconfig.json(JS项目)或tsconfig.json(TS项目)中添加baseUrl配置:

{
  "compilerOptions": {
    "baseUrl": "."
  }
}

之后即可用根路径导入:

import { cn } from '@/utils/cn'

3. 检查utils文件夹的index.js(若存在)

如果utils文件夹下有index.js,需要确保它重新导出了cn函数,否则无法通过/utils/路径直接导入:

// utils/index.js
export { cn } from './cn'

配置后即可用:

import { cn } from '../utils' // 或@/utils

4. 额外排查点

  • 确认clsx和tailwind-merge已安装:
    npm install clsx tailwind-merge
    
  • 重启Next.js开发服务器,避免缓存导致的导入异常
  • 检查cn.js文件是否存在拼写错误或语法问题

修改后的Separator组件示例

import { cn } from '../utils/cn'
import { SeparatorPrimitive } from '@/components/ui/separator' // 确保SeparatorPrimitive路径正确

const Separator = React.forwardRef((
  { className, orientation = "horizontal", decorative = true, ...props },
  ref
) => (
  <SeparatorPrimitive.Root
    ref={ref}
    decorative={decorative}
    orientation={orientation}
    className={cn(
      "shrink-0 bg-border",
      orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
      className
    )}
    {...props} />
))
Separator.displayName = SeparatorPrimitive.Root.displayName

export { Separator }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 15:02:40