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

React Router Framework关闭SSR后styled-components仍无法使用的问题求助

React Router Framework关闭SSR后styled-components仍无法使用的问题求助

我用Vite搭建了一个React Router Framework项目,想在里面使用styled-components,但一直遭遇SSR相关的错误。下面是我写的最小复现示例:

项目代码文件

app/routes.tsx

import { type RouteConfig, index } from "@react-router/dev/routes";

export default [index("routes/home.tsx")] satisfies RouteConfig;

app/routes/home.tsx

import type { Route } from "./+types/home";
import styled from "styled-components";

export function meta({}: Route.MetaArgs) {
  return [
    { title: "New React Router App" },
    { name: "description", content: "Welcome to React Router!" },
  ];
}

const Text = ({className}: {className?: string}) => <div><p className={className}>MY TEXT</p></div>
const StyledText = styled(Text)`
  color: red;
`

export default function Home() {
  return <main><StyledText /></main>
}

运行时错误信息

运行这个示例后,我得到了如下错误:

[vite] Internal server error: __vite_ssr_import_2__.default is not a function
      at eval (*project-root*/app/routes/home.tsx:34:49)
      at instantiateModule (file:///*project-root*/node_modules/vite/dist/node/chunks/dep-CHZK6zbr.js:52974:5)

已尝试的SSR关闭配置

我知道styled-components在SSR环境下需要特殊配置,但我已经明确关闭了SSR:

react-router.config.ts

import type { Config } from "@react-router/dev/config";

export default {
  ssr: false,
} satisfies Config;

vite.config.ts

import { reactRouter } from "@react-router/dev/vite";
import tailwindcss from "@tailwindcss/vite";
import { defineConfig } from "vite";
import tsconfigPaths from "vite-tsconfig-paths";

export default defineConfig({
  plugins: [tailwindcss(), reactRouter(), tsconfigPaths()],
  build: {
    cssMinify: true,
    ssr: false,
}});

我实在搞不懂为什么还是会触发SSR相关的操作。这个项目我完全没打算用SSR,也不想花精力去配置styled-components的SSR兼容,同时我也不想换成React Router Library,因为Framework版本有我需要的其他实用功能。

想请教大家:我哪里配置错了?怎么才能彻底关闭SSR来解决这个问题?

备注:内容来源于stack exchange,提问作者TimurTimergalin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 15:29:29