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
輸出中定義)載入到瀏覽器快取中。