links

links

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

¥The links function defines which <link> elements to add to the page when the user visits a route.

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",
    },
  ];
};

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

¥There are two types of link descriptors you can return:

HtmlLinkDescriptor

这是一个普通 <link {...props} /> 元素的对象表示。查看 link API 的 MDN 文档

¥This is an object representation of a normal <link {...props} /> element. View the MDN docs for the link API.

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

¥The links export from a route should return an array of HtmlLinkDescriptor objects.

示例:

¥Examples:

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 获得相同的行为。

¥These descriptors allow you to prefetch the resources for a page the user is likely to navigate to. While this API is useful, you might get more mileage out of <Link prefetch="render"> instead. But if you'd like, you can get the same behavior with this API.

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

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

¥This loads up the JavaScript modules, loader data, and the stylesheets (defined in the links exports of the next routes) into the browser cache before the user even navigates there.

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

Remix v2.17 中文网 - 粤ICP备13048890号