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

Turborepo中Client组件打包报错:tsup移除use client指令如何解决?

解决Turborepo中tsup移除use client指令及styled-components打包问题

一、保留use client指令的解决方案

tsup打包时会默认移除模块级指令,导致Next.js无法识别客户端组件。直接配置tsup的banner选项,就能在输出的每个客户端组件文件顶部自动注入use client:

在UI包的tsup.config.ts中添加如下配置:

import { defineConfig } from "tsup";

export default defineConfig({
  // 保留原有其他配置
  banner: {
    js: '"use client";',
  },
});

配置后,tsup会自动在所有输出的JS/JSX/TS/TSX文件顶部加上use client指令,无需手动在源文件重复添加(源文件已添加也不会冲突)。

二、解决styled-components打包错误

针对TypeError: styled_components__WEBPACK_IMPORTED_MODULE_2__.div is not a function的错误,本质是webpack未正确识别styled-components的依赖关系,可按以下步骤处理:

  1. 在UI包的package.json中,将styled-components声明为peerDependencies,确保使用该UI包的应用统一管理依赖版本:
{
  "peerDependencies": {
    "styled-components": "^6.0.0"
  },
  "devDependencies": {
    "styled-components": "^6.0.0"
  }
}
  1. 配置tsup将styled-components设为外部依赖,避免将其打包进UI包产物:
    在tsup.config.ts中添加external选项:
export default defineConfig({
  // 保留原有其他配置
  external: ["styled-components"],
});
  1. 在使用该UI包的Next.js应用中,确保已安装styled-components:
npm install styled-components
# 或
yarn add styled-components

三、额外注意事项

  • 上述配置对JS和TSX类型的组件均适用,无需区分文件类型。
  • 若使用TypeScript,需确保UI包的tsconfig.json中正确配置React相关编译选项(如jsx: "react-jsx")。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:22:54