简体   繁体   English

将 a.client 后缀添加到 my.jsx 或 .tsx 文件会破坏 Remix 中的导入

[英]adding a .client suffix to my .jsx or .tsx file breaks the import in Remix

I'm ultimately trying to get remix-utils to help me render a client-side-only component.我最终试图让 remix-utils 来帮助我渲染一个仅客户端组件。 Was lead to believe that a.client.tsx or.client.jsx file would help (even though I can't find it in the docs anywhere)导致相信 a.client.tsx 或 .client.jsx 文件会有所帮助(即使我在文档中的任何地方都找不到它)

So I have this file:所以我有这个文件:

// app/components/Test.client.jsx
export default function Test() {
  return <div>This is a test</div>;
}

being imported into my index.tsx file:被导入到我的 index.tsx 文件中:

// app/routes/index.tsx
import Test from "~/components/Test.client";

export default function Index() {
  return (
    <div style={{ fontFamily: "system-ui, sans-serif", lineHeight: "1.4" }}>
      <h1>Welcome to Remix</h1>
      <Test />
    </div>
  );
}

Why won't this work?为什么这行不通? I've done this exact setup in a vanilla TypeScript app, and it works fine.我已经在 vanilla TypeScript 应用程序中完成了这个精确的设置,并且工作正常。 Also, if I just remove the.client suffix it will import fine, but adding.client at the end of the file name somehow breaks the app and produces this error:此外,如果我只是删除 .client 后缀,它将正常导入,但在文件名末尾添加 .client 会以某种方式破坏应用程序并产生此错误:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.错误:元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件)但得到:对象。 You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.您可能忘记从定义它的文件中导出您的组件,或者您可能混淆了默认导入和命名导入。

The .client suffix tells Remix to only include this in the client bundle. .client后缀告诉 Remix 只将其包含在客户端包中。

Remember that Remix will render your route component on both the server and the client.请记住,Remix 将在服务器和客户端上呈现您的路由组件。 By making Test a client-only component, it breaks if your route is server rendered ( Test is essentially undefined on the server).通过使Test成为仅客户端组件,如果您的路由是服务器呈现的,它就会中断( Test在服务器上基本上是undefined的)。

If the component is truly client only, then you also need to use the <ClientOnly/> wrapper from remix utils.如果该组件确实仅供客户端使用,那么您还需要使用 remix utils 中的<ClientOnly/>包装器。

<ClientOnly>
  {() => <Test/>}
</ClientOnly>

This ensures that Remix does not try to render the component server-side.这确保 Remix 不会尝试在服务器端呈现组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM