---
title: "图像优化"
description: "了解如何使用 Nuxt Image 优化 Nuxt 应用中的图像。"
canonical_url: "https://nuxt.zhcndoc.com/docs/4.x/getting-started/images"
---
# 图像优化

> 了解如何使用 Nuxt Image 优化 Nuxt 应用中的图像。

Nuxt 提供了一个核心模块（[`@nuxt/image`](https://nuxt.zhcndoc.com/modules/image)），用于调整图像尺寸、转换图像格式，并在应用中提供经过优化的图像：

- **可直接替换：** 在原本使用 `<img>` 和 `<picture>` 的位置，改用 [`<NuxtImg>`](https://nuxt.zhcndoc.com/docs/4.x/api/components/nuxt-img) 和 [`<NuxtPicture>`](https://nuxt.zhcndoc.com/docs/4.x/api/components/nuxt-picture)。
- **内置缩放器：** 无需配置，即可使用默认提供商 [IPX](https://nuxt.zhcndoc.com/modules/image/providers/ipx) 优化本地图像和远程图像。
- **支持 40 多种提供商：** 使用 CDN 或 CMS 的图像服务，也可以[编写自己的提供商](https://nuxt.zhcndoc.com/modules/image/advanced/custom-provider)，避免供应商锁定。
- **支持响应式：** 针对不同屏幕尺寸和设备像素密度提供相应尺寸的图像。
- **现代格式：** 将图像转换为浏览器支持的 WebP 或 AVIF 格式。
- **加快页面加载：** 使用原生懒加载，仅在图像进入视口时加载，并在加载期间显示占位图。
- **保持视觉稳定：** 为图像预留空间，设置 `width` 和 `height` 以避免[布局偏移](https://web.dev/articles/cls)。

## 安装

将 Nuxt Image 模块添加到项目中：

```bash [Terminal]
npx nuxt add image
```

此命令会安装 `@nuxt/image`，并将其添加到 `nuxt.config` 的 `modules` 中。

::note
如果未安装该模块就在开发环境中使用 `<NuxtImg>` 或 `<NuxtPicture>`，Nuxt 会检测到这一情况并提示你安装 `@nuxt/image`。
::

## 用法

使用 `<NuxtImg>` 替代 `<img>`，使用 `<NuxtPicture>` 替代 `<picture>`。无需手动导入：

::code-group
```vue [NuxtImg]
<template>
  <NuxtImg
    src="/nuxt.png"
    alt="Nuxt logo"
    width="300"
    height="80"
  />
</template>
```

```vue [NuxtPicture]
<template>
  <NuxtPicture
    src="/nuxt.png"
    alt="Nuxt logo"
    width="300"
    height="80"
    format="avif,webp"
  />
</template>
```
::

`src` 属性可以指向[本地](#local-images)或[远程](#remote-images)图像。

## 本地图像 {#local-images}

将图像存储在 [`public/`](https://nuxt.zhcndoc.com/docs/4.x/directory-structure/public) 目录中，并使用根路径（`/`）引用。例如，`public/profile.png` 可通过 `/profile.png` 访问：

```vue [app/pages/index.vue]
<template>
  <NuxtImg
    src="/profile.png"
    alt="Picture of the author"
    width="500"
    height="500"
  />
</template>
```

Nuxt Image 会根据指定的 `width` 和 `height` 调整图像尺寸。浏览器也会使用这些值在图像加载前预留空间，从而避免布局偏移。Nuxt Image 不会读取文件的固有尺寸，因此对于未通过 CSS 设置尺寸的图像，请务必指定 `width` 和 `height`。

默认情况下，Nuxt Image 使用 [IPX](https://nuxt.zhcndoc.com/modules/image/providers/ipx)，这是一种运行在 Nuxt 服务器上的自托管优化器。使用 `nuxt generate` 预渲染站点时，Nuxt Image 会改为在构建时优化图像。

预渲染只会生成服务端渲染的 HTML 中包含的图像尺寸。仅在浏览器中渲染的图像（例如模态框或仅客户端组件中的图像）不会生成对应文件，因此访问其 URL 会返回 404。请将这些图像列入 `nitro.prerender.routes`，或使用[图像提供商](#image-providers)。详情请参阅[静态图像](https://nuxt.zhcndoc.com/modules/image/advanced/static-images)。

::warning
IPX 无法在 Worker 运行时中运行。部署到 Cloudflare Workers 等环境时，Nuxt Image 会直接提供原始图像，不进行优化。请配置 `cloudflare` 等[图像提供商](#image-providers)来优化图像。
::

::note
Nuxt Image 不会处理 [`app/assets/`](https://nuxt.zhcndoc.com/docs/4.x/directory-structure/app/assets) 目录中的图像，因为这些图像由构建工具管理。若要将源图像存放在 `public/` 之外，请设置 [`image.dir`](https://nuxt.zhcndoc.com/modules/image/configuration#dir) 选项。
::

## 响应式图像 {#responsive-images}

使用 `sizes` prop 生成多个图像宽度，让浏览器根据屏幕选择合适的尺寸。每个值从对应屏幕尺寸起生效。默认情况下，屏幕尺寸与 [Tailwind CSS 断点](https://nuxt.zhcndoc.com/modules/image/configuration#screens)一致：

```vue [app/pages/index.vue]
<template>
  <NuxtImg
    src="/hero.jpg"
    alt="Mountains at sunrise"
    width="1600"
    height="900"
    sizes="100vw md:50vw xl:800px"
  />
</template>
```

在此示例中，小屏幕上的图像占满屏幕宽度；从 `md` 断点起占一半宽度；从 `xl` 断点起宽度为 800 像素。Nuxt Image 会为每种尺寸生成一个 `srcset` 图像，并分别提供 1x 和 2x 像素密度版本。`sizes` prop 不会设置图像的显示宽度，请使用 CSS 设置图像宽度。

未设置 `sizes` 的图像（例如图标或头像）默认会生成 1x 和 2x 版本，因此在高像素密度屏幕上仍能保持清晰。若要更改像素密度，可对单张图像使用 [`densities` prop](https://nuxt.zhcndoc.com/modules/image/usage/nuxt-img#densities)，或通过 [`image.densities`](https://nuxt.zhcndoc.com/modules/image/configuration#densities) 选项统一设置。

## 图像格式 {#image-formats}

使用 `format` prop 将图像转换为现代格式：

```vue
<template>
  <NuxtImg
    src="/hero.jpg"
    alt="Mountains at sunrise"
    format="webp"
  />
</template>
```

若要提供各浏览器支持的最佳格式，请使用 `<NuxtPicture>`。它会渲染一个 `<picture>` 元素，为每种格式提供一个 source，并以 JPEG 或 PNG 等旧格式作为后备：

```vue
<template>
  <NuxtPicture
    src="/hero.jpg"
    alt="Mountains at sunrise"
    format="avif,webp"
  />
</template>
```

## 加载优先级 {#loading-priority}

首屏以下的图像可以等用户滚动到附近时再加载。设置 `loading="lazy"`，即可仅在图像进入视口时加载：

```vue
<template>
  <NuxtImg
    src="/gallery/sunset.jpg"
    alt="Sunset over the sea"
    width="400"
    height="300"
    loading="lazy"
  />
</template>
```

作为页面[最大内容绘制 (LCP)](https://web.dev/articles/lcp)元素的图像（例如主视觉图）必须尽早加载。使用 `preload` prop 在页面 head 中添加具有较高获取优先级的 `<link rel="preload">` 标签：

```vue
<template>
  <NuxtImg
    src="/hero.jpg"
    alt="Mountains at sunrise"
    width="1600"
    height="900"
    :preload="{ fetchPriority: 'high' }"
  />
</template>
```

## 占位图 {#placeholders}

若要在完整图像加载期间显示模糊的低画质版本，请添加 `placeholder` prop：

```vue
<template>
  <NuxtImg
    src="/hero.jpg"
    alt="Mountains at sunrise"
    width="1600"
    height="900"
    placeholder
  />
</template>
```

`<NuxtImg>` 会在浏览器中将占位图替换为完整图像，因此占位图功能需要 JavaScript。若未启用 JavaScript，页面会一直显示占位图。

你也可以传入自己的占位图，或设置占位图的尺寸、画质和模糊程度。所有选项请参阅 [`placeholder` prop](https://nuxt.zhcndoc.com/modules/image/usage/nuxt-img#placeholder)。

## 远程图像 {#remote-images}

若要使用远程图像，请在 `src` 属性中传入其 URL：

```vue [app/pages/index.vue]
<template>
  <NuxtImg
    src="https://images.unsplash.com/photo-1501785888041-af3ef285b470"
    alt="Lake surrounded by mountains"
    width="500"
    height="500"
  />
</template>
```

为防止其他网站利用你的服务器优化互联网上的任意图像，Nuxt Image 只会优化你允许的域名中的远程图像。请将这些域名添加到 `nuxt.config` 的 `image.domains` 选项中：

```ts [nuxt.config.ts]
export default defineNuxtConfig({
  modules: ['@nuxt/image'],
  image: {
    domains: ['images.unsplash.com'],
  },
})
```

使用默认的 IPX 提供商时，Nuxt Image 会通过原始 URL 渲染其他域名的图像，不进行优化。其他[提供商](#image-providers)对此类图像的处理方式可能不同。

## 图像提供商 {#image-providers}

如果你已将图像托管在图像 CDN 或无头 CMS 上，Nuxt Image 可以使用其转换服务替代 IPX。Nuxt Image 支持 [40 多种提供商](https://nuxt.zhcndoc.com/modules/image/providers)，例如 Cloudinary、Imgix、Sanity 和 Storyblok。部署到 Vercel、Netlify 或 AWS Amplify 时，Nuxt Image 会自动检测并使用平台提供的图像服务。

若要使用某个提供商，请将其设为默认 `provider`，并在 `nuxt.config` 中进行配置：

```ts [nuxt.config.ts]
export default defineNuxtConfig({
  modules: ['@nuxt/image'],
  image: {
    provider: 'cloudinary',
    cloudinary: {
      baseURL: 'https://res.cloudinary.com/<your-cloud-name>/image/upload',
    },
  },
})
```

此时，图像的 `src` 是该提供商上的路径：

```vue
<template>
  <NuxtImg
    src="/blog/cover.jpg"
    alt="Blog post cover"
    width="800"
    height="450"
  />
</template>
```

你也可以使用 [`provider`](https://nuxt.zhcndoc.com/modules/image/usage/nuxt-img#provider) prop 为单张图像指定提供商。

## 后续步骤

Nuxt Image 的完整功能说明请参阅：

- [`<NuxtImg>`](https://nuxt.zhcndoc.com/modules/image/usage/nuxt-img)：图像组件的所有 props。
- [`<NuxtPicture>`](https://nuxt.zhcndoc.com/modules/image/usage/nuxt-picture)：提供多种图像格式。
- [`useImage()`](https://nuxt.zhcndoc.com/modules/image/usage/use-image)：在代码中生成优化后的图像 URL，例如用于 CSS 背景。
- [配置](https://nuxt.zhcndoc.com/modules/image/configuration)：设置画质、格式、屏幕尺寸和预设等默认值。


## Sitemap

See the full [sitemap](https://nuxt.zhcndoc.com/sitemap.md) for all pages.
