链接

links

links 函数定义了当用户访问路由时要添加到页面中的哪些 <link> 元素

import type { LinksFunction } from "@remix-run/node"; // or cloudflare/deno

export const links: LinksFunction = () => {
  return [
    {
      rel: "icon",
      href: "/favicon.png",
      type: "image/png",
    },
    {
      rel: "stylesheet",
      href: "https://example.com/some/styles.css",
    },
    { page: "/users/123" },
    {
      rel: "preload",
      href: "/images/banner.jpg",
      as: "image",
    },
  ];
};

您可以返回两种类型的链接描述符

HtmlLinkDescriptor

这是正常 <link {...props} /> 元素的对象表示。 查看 MDN 文档以了解链接 API

路由中的 links 导出应该返回一个 HtmlLinkDescriptor 对象数组。

示例

import type { LinksFunction } from "@remix-run/node"; // or cloudflare/deno

import stylesHref from "../styles/something.css";

export const links: LinksFunction = () => {
  return [
    // add a favicon
    {
      rel: "icon",
      href: "/favicon.png",
      type: "image/png",
    },

    // add an external stylesheet
    {
      rel: "stylesheet",
      href: "https://example.com/some/styles.css",
      crossOrigin: "anonymous",
    },

    // add a local stylesheet, remix will fingerprint the file name for
    // production caching
    { rel: "stylesheet", href: stylesHref },

    // prefetch an image into the browser cache that the user is likely to see
    // as they interact with this page, perhaps they click a button to reveal in
    // a summary/details element
    {
      rel: "prefetch",
      as: "image",
      href: "/img/bunny.jpg",
    },

    // only prefetch it if they're on a bigger screen
    {
      rel: "prefetch",
      as: "image",
      href: "/img/bunny.jpg",
      media: "(min-width: 1000px)",
    },
  ];
};

PageLinkDescriptor

这些描述符允许您预取用户可能要导航到的页面的资源。虽然此 API 有用,但您可能更常使用 <Link prefetch="render">。但如果您愿意,可以使用此 API 获得相同的效果。

export const links: LinksFunction = () => {
  return [{ page: "/posts/public" }];
};

这会在用户甚至导航到该页面之前,将 JavaScript 模块、加载器数据和样式表(在下一路由的 links 导出中定义)加载到浏览器缓存中。

请谨慎使用此功能。您不希望为用户可能永远不会访问的页面下载 10MB 的 JavaScript 和数据。

文档和示例的许可证为 MIT