如何优化图片和字体
Next.js 带有自动图片和字体优化功能,可实现更好的性能和用户体验。本页将指导你如何开始使用它们。
¥Next.js comes with automatic image and font optimization for better performance and user experience. This page will guide you through how to start using them.
处理静态资源
¥Handling static assets
你可以将静态文件(如图片和字体)存储在根目录中名为 public
的文件夹下。然后,你的代码可以从基本 URL (/
) 开始引用 public
内的文件。
¥You can store static files, like images and fonts, under a folder called public
in the root directory. Files inside public
can then be referenced by your code starting from the base URL (/
).
优化图片
¥Optimizing images
Next.js <Image>
组件扩展了 HTML <img>
元素以提供:
¥The Next.js <Image>
component extends the HTML <img>
element to provide:
-
大小优化:使用 WebP 和 AVIF 等现代图片格式自动为每台设备提供正确大小的图片。
¥Size optimization: Automatically serving correctly sized images for each device, using modern image formats like WebP and AVIF.
-
视觉稳定性:在加载图片时自动阻止 布局转变。
¥Visual stability: Preventing layout shift automatically when images are loading.
-
更快的页面加载:仅在图片进入视口时使用原生浏览器延迟加载加载图片,并使用可选的模糊占位符。
¥Faster page loads: Only loading images when they enter the viewport using native browser lazy loading, with optional blur-up placeholders.
-
资源灵活性:按需调整图片大小,即使图片存储在远程服务器上。
¥Asset flexibility: Resizing images on-demand, even images stored on remote servers.
要开始使用 <Image>
,请从 next/image
导入它并在组件中渲染它。
¥To start using <Image>
, import it from next/image
and render it within your component.
import Image from 'next/image'
export default function Page() {
return <Image src="" alt="" />
}
import Image from 'next/image'
export default function Page() {
return <Image src="" alt="" />
}
¥The src
property can be a local or remote image.
本地图片
¥Local images
要使用本地图片,请从 public
文件夹 中 import
你的 .jpg
、.png
或 .webp
图片文件。
¥To use a local image, import
your .jpg
, .png
, or .webp
image files from your public
folder.
import Image from 'next/image'
import profilePic from './me.png'
export default function Page() {
return (
<Image
src={profilePic}
alt="Picture of the author"
// width={500} automatically provided
// height={500} automatically provided
// blurDataURL="data:..." automatically provided
// placeholder="blur" // Optional blur-up while loading
/>
)
}
import Image from 'next/image'
import profilePic from './me.png'
export default function Page() {
return (
<Image
src={profilePic}
alt="Picture of the author"
// width={500} automatically provided
// height={500} automatically provided
// blurDataURL="data:..." automatically provided
// placeholder="blur" // Optional blur-up while loading
/>
)
}
Next.js 将根据导入的文件自动确定图片的固有 width
和 height
。这些值用于确定图片比例并在图片加载时防止 累积布局偏移。
¥Next.js will automatically determine the intrinsic width
and height
of your image based on the imported file. These values are used to determine the image ratio and prevent Cumulative Layout Shift while your image is loading.
远程图片
¥Remote images
要使用远程图片,你可以为 src
属性提供 URL 字符串。
¥To use a remote image, you can provide a URL string for the src
property.
import Image from 'next/image'
export default function Page() {
return (
<Image
src="https://s3.amazonaws.com/my-bucket/profile.png"
alt="Picture of the author"
width={500}
height={500}
/>
)
}
import Image from 'next/image'
export default function Page() {
return (
<Image
src="https://s3.amazonaws.com/my-bucket/profile.png"
alt="Picture of the author"
width={500}
height={500}
/>
)
}
由于 Next.js 在构建过程中无法访问远程文件,因此你需要手动提供 width
、height
和可选的 blurDataURL
属性。width
和 height
属性用于推断图片的正确纵横比,并避免图片加载时布局偏移。
¥Since Next.js does not have access to remote files during the build process, you'll need to provide the width
, height
and optional blurDataURL
props manually. The width
and height
attributes are used to infer the correct aspect ratio of image and avoid layout shift from the image loading in.
然后,为了安全地允许来自远程服务器的图片,你需要在 next.config.js
中定义支持的 URL 模式列表。尽可能具体,以防止恶意使用。例如,以下配置将仅允许来自特定 AWS S3 存储桶的图片:
¥Then, to safely allow images from remote servers, you need to define a list of supported URL patterns in next.config.js
. Be as specific as possible to prevent malicious usage. For example, the following configuration will only allow images from a specific AWS S3 bucket:
import { NextConfig } from 'next'
const config: NextConfig = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 's3.amazonaws.com',
port: '',
pathname: '/my-bucket/**',
search: '',
},
],
},
}
export default config
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 's3.amazonaws.com',
port: '',
pathname: '/my-bucket/**',
search: '',
},
],
},
}
优化字体
¥Optimizing fonts
next/font
模块会自动优化你的字体并删除外部网络请求,以提高隐私和性能。
¥The next/font
module automatically optimizes your fonts and removes external network requests for improved privacy and performance.
它包括任何字体文件的内置自动自托管。这意味着你可以最佳地加载 Web 字体而不会发生布局偏移。
¥It includes built-in automatic self-hosting for any font file. This means you can optimally load web fonts with no layout shift.
要开始使用 next/font
,请从 next/font/local
或 next/font/google
导入它,使用适当的选项将其作为函数调用,然后设置要应用字体的元素的 className
。例如:
¥To start using next/font
, import it from next/font/local
or next/font/google
, call it as a function with the appropriate options, and set the className
of the element you want to apply the font to. For example:
import { Geist } from 'next/font/google'
const geist = Geist({
subsets: ['latin'],
})
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" className={geist.className}>
<body>{children}</body>
</html>
)
}
import { Geist } from 'next/font/google'
const geist = Geist({
subsets: ['latin'],
})
export default function Layout({ children }) {
return (
<html className={geist.className}>
<body>{children}</body>
</html>
)
}
Google 字体
¥Google fonts
你可以自动自托管任何 Google 字体。字体包含在部署中,并从与你的部署相同的域提供,这意味着当用户访问你的网站时,浏览器不会向 Google 发送任何请求。
¥You can automatically self-host any Google Font. Fonts are included in the deployment and served from the same domain as your deployment, meaning no requests are sent to Google by the browser when the user visits your site.
要开始使用 Google 字体,请从 next/font/google
导入你选择的字体:
¥To start using a Google Font, import your chosen font from next/font/google
:
import { Geist } from 'next/font/google'
const geist = Geist({
subsets: ['latin'],
})
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className={geist.className}>
<body>{children}</body>
</html>
)
}
import { Geist } from 'next/font/google'
const geist = Geist({
subsets: ['latin'],
})
export default function RootLayout({ children }) {
return (
<html lang="en" className={geist.className}>
<body>{children}</body>
</html>
)
}
我们建议使用 可变字体 以获得最佳性能和灵活性。但如果不能使用可变字体,则需要指定权重:
¥We recommend using variable fonts for the best performance and flexibility. But if you can't use a variable font, you will need to specify a weight:
import { Roboto } from 'next/font/google'
const roboto = Roboto({
weight: '400',
subsets: ['latin'],
})
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className={roboto.className}>
<body>{children}</body>
</html>
)
}
import { Roboto } from 'next/font/google'
const roboto = Roboto({
weight: '400',
subsets: ['latin'],
})
export default function RootLayout({ children }) {
return (
<html lang="en" className={roboto.className}>
<body>{children}</body>
</html>
)
}
本地字体
¥Local fonts
要使用本地字体,请从 next/font/local
导入字体并在 public
文件夹 中指定本地字体文件的 src
。
¥To use a local font, import your font from next/font/local
and specify the src
of your local font file in the public
folder.
import localFont from 'next/font/local'
const myFont = localFont({
src: './my-font.woff2',
})
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className={myFont.className}>
<body>{children}</body>
</html>
)
}
import localFont from 'next/font/local'
const myFont = localFont({
src: './my-font.woff2',
})
export default function RootLayout({ children }) {
return (
<html lang="en" className={myFont.className}>
<body>{children}</body>
</html>
)
}
如果你想对单个字体系列使用多个文件,src
可以是一个数组:
¥If you want to use multiple files for a single font family, src
can be an array:
const roboto = localFont({
src: [
{
path: './Roboto-Regular.woff2',
weight: '400',
style: 'normal',
},
{
path: './Roboto-Italic.woff2',
weight: '400',
style: 'italic',
},
{
path: './Roboto-Bold.woff2',
weight: '700',
style: 'normal',
},
{
path: './Roboto-BoldItalic.woff2',
weight: '700',
style: 'italic',
},
],
})