跳转到内容

links

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 模块、加载器数据和样式表(在下一个路由的链接导出中定义)加载到浏览器缓存中。

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