@desource/image-svelte

中文文档
0.5.0发布于 2026/11/01MITTypeScriptES Module构建来源已验证近 30 天下载 1.7万

High-quality image optimization for Svelte and SvelteKit with responsive output, deployment-aware provider selection, dozens of built-in provider modules, and IPX.

原始使用文档
文档目录19 节
  1. Why DeSource Image for Svelte?
  2. How it compares
  3. Install
  4. Configure SvelteKit
  5. DsImage component
  6. DsPicture component
  7. Custom rendering snippet
  8. Actions for native elements
  9. Attachments for Svelte 5.29+
  10. Bind one configuration once
  11. SSR prop helpers
  12. Responsive images, placeholders, and preloads
  13. Callable image helper
  14. Providers and presets
  15. Production deployment
  16. Vercel native images
  17. SvelteKit with production IPX
  18. Links
  19. License

DeSource Image
Optimized images for Svelte and SvelteKit

High-quality image optimization with responsive, provider-first and SSR-friendly workflow for Svelte and SvelteKit.

npm version Coverage SonarCloud Ask Context7 Ask DeepWiki MIT license

AI-assisted development moves ideas into working products quickly. DeSource Image keeps image preparation inside that development loop. Add one suitable local or remote source, then control its output with component props.

Keep /img/hero.jpg instead of exporting hero-480.webp, hero-960.webp, and hero-1600.webp. DeSource Image turns one image input into provider URLs, responsive srcset, <picture> sources, placeholders, preload metadata, presets, aliases, source validation, and local IPX routes.

For MVPs and everyday product development, image quality becomes a code edit. Change quality={80} to quality={65} and keep the same source file, component, and URL.

@desource/image-svelte renders native image markup without wrapper elements and provides components, actions, Svelte 5.29+ attachments, SSR prop helpers, Vite dev/preview middleware, and production server handlers. Local paths and dynamic URLs use the same component API.

Provider configuration is optional. On Vercel, Netlify, or AWS Amplify, DeSource Image selects the platform image service from the deployment environment. Everywhere else, it falls back to the built-in IPX path. An explicit provider always wins.

The package requires Svelte 5.29 or newer when using attachments. Components and actions require Svelte 5.

Why DeSource Image for Svelte?

SvelteKit's @sveltejs/enhanced-img is a strong build-time tool for imported local files. DeSource Image transforms local images on demand and accepts sources from a CMS, database, API, object store, CDN, or user upload through the same component API.

  • Built for fast product iterations. Change image quality, format, crop, or responsive sizes in Svelte. Source files and filenames stay unchanged.
  • Local and dynamic sources. Use a local path, CMS response, database value, API result, object-store URL, CDN URL, or user upload with the same component props.
  • Deployment-aware provider selection. Leave provider on auto. DeSource Image detects Vercel, Netlify, or AWS Amplify and uses IPX for local or other environments.
  • Native framework APIs. Use components, actions, Svelte 5 attachments, snippets, or SSR prop helpers. Output remains native <img> and <picture> markup.
  • Dozens of built-in provider modules. Import one provider subpath, use the complete registry, or register a typed custom provider.
  • Built-in local optimizer. Vite middleware and SvelteKit server handlers can serve IPX transformations without a separate image service.
  • Responsive images and modern formats. Generate width or density candidates, breakpoint-aware sizes, ordered AVIF/WebP sources, and a fallback image.

How it compares

OptionBest fitHow optimization is selectedChoose DeSource Image when
@sveltejs/enhanced-imgStatic local assets transformed during the Vite buildImages are processed at build time. The deployment target does not switch them to its runtime image service.You want local images transformed on demand to save your time. Your images arrive from a CMS, database, API, object store, or CDN, or the same source should use IPX locally and the deployment platform's optimizer in production.
Unpic SvelteCross-framework responsive images already hosted on recognizable CDN or CMS URLsDetects the provider from each src URL. Local or unknown sources need a fallback or explicit provider; the deployment itself is not the selection signal.Vercel, Netlify, or AWS Amplify should choose the optimizer for every source, including relative paths, and you also need presets, aliases, source rules, <picture>, or server adapters.

Use enhanced:img when every image is imported at build time and you want all variants produced during that build with no runtime optimizer. Choose DeSource Image for local images transformed on demand, dynamic sources, or an optimizer that follows the deployment.

Install

npm install @desource/image-svelte

Install ipx when the application serves local /_ipx transformations in development, preview, or production:

npm install ipx

Keep ipx in production dependencies when using the production server adapter. It is optional when every image uses a hosted provider. Add @desource/image as a direct dependency only when the application imports provider factories or utilities from it.

Configure SvelteKit

Add the Vite integration after installing ipx:

// vite.config.ts
import { dsImage } from '@desource/image-svelte/vite';
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [dsImage({ dirs: ['static'] }), sveltekit()]
});

The plugin serves /_ipx in Vite development and preview. It also bakes the detected provider into client and server bundles so hydration uses the same provider.

Set shared configuration once in a root layout when defaults, presets, aliases, or validation rules are needed:

<!-- src/routes/+layout.svelte -->
<script lang="ts">
  import { setDsImageConfig } from '@desource/image-svelte';
  import { cloudinaryProvider } from '@desource/image/providers/cloudinary';

  setDsImageConfig({
    provider: 'cloudinary',
    quality: 80,
    screens: { sm: 640, md: 768, lg: 1024 },
    domains: ['images.example.com'],
    providers: {
      cloudinary: cloudinaryProvider({ cloudName: 'demo' })
    },
    presets: {
      avatar: { width: 96, height: 96, fit: 'cover', format: 'webp' }
    }
  });

  let { children } = $props();
</script>

{@render children()}

Configuration is inherited through Svelte context and resolved once per config object. With no explicit provider, the shared runtime detects Vercel, Netlify, or AWS Amplify from the build environment and falls back to IPX.

DsImage component

<script lang="ts">
  import { DsImage } from '@desource/image-svelte';

  let loaded = $state(false);
</script>

<DsImage
  src="/img/hero.jpg"
  alt="Aurora above a mountain lake"
  width={1600}
  height={900}
  sizes="100vw md:50vw lg:800px"
  format="webp"
  quality={82}
  placeholder
  preload={{ fetchPriority: 'high' }}
  class="hero"
  onload={() => (loaded = true)}
/>

alt is required. Native image attributes and Svelte event properties pass through to the generated <img>.

DsPicture component

<script lang="ts">
  import { DsPicture } from '@desource/image-svelte';
</script>

<DsPicture
  src="/img/hero.jpg"
  alt="Responsive mountain landscape"
  width={1600}
  height={900}
  sizes="100vw md:50vw lg:800px"
  formats={['avif', 'webp']}
  fallbackFormat="jpg"
  class="hero-frame"
  imgAttrs={{ class: 'hero' }}
/>

This renders native <picture>, <source>, and <img> elements. Comma-separated format="avif,webp", array format, and the legacyFormat alias are supported.

Custom rendering snippet

Use custom with the children snippet when the image needs custom surrounding markup while retaining generated attributes and placeholder state:

<DsImage src="/img/hero.jpg" alt="Hero" width={1200} placeholder custom>
  {#snippet children({ imgAttrs, src, isLoaded })}
    <figure data-src={src} data-loaded={isLoaded}>
      <img {...imgAttrs} />
      <figcaption>Mountain lake</figcaption>
    </figure>
  {/snippet}
</DsImage>

Actions for native elements

Actions provide the same reactive behavior on regular elements:

<script lang="ts">
  import { dsImageAction, dsPictureAction } from '@desource/image-svelte';

  let width = $state(720);
  const imageOptions = $derived({
    src: '/img/card.jpg',
    alt: 'A coastal village',
    width,
    height: 480,
    densities: '1x 2x',
    placeholder: true
  });
</script>

<img alt="A coastal village" use:dsImageAction={imageOptions} />

<picture
  use:dsPictureAction={{
    src: '/img/card.jpg',
    alt: 'A coastal village at sunset',
    width,
    height: 480,
    formats: ['avif', 'webp']
  }}
>
  <img alt="A coastal village at sunset" />
</picture>

The picture action requires one fallback <img> and manages generated <source> elements around it.

Attachments for Svelte 5.29+

Attachments expose the same engine with Svelte's newer element lifecycle API:

<script lang="ts">
  import { dsImageAttachment, dsPictureAttachment } from '@desource/image-svelte';
</script>

<img
  alt="Mountain lake"
  {@attach dsImageAttachment({
    src: '/img/hero.jpg',
    alt: 'Mountain lake',
    width: 960,
    format: 'webp'
  })}
/>

<picture
  {@attach dsPictureAttachment({
    src: '/img/hero.jpg',
    alt: 'Mountain lake',
    width: 960,
    formats: ['avif', 'webp']
  })}
>
  <img alt="Mountain lake" />
</picture>

Actions and attachments support updates, load/error callbacks, placeholder decoding, class cleanup, and onStateChange.

Bind one configuration once

Use createDsImageBindings() when several native elements share an explicit configuration:

<script lang="ts">
  import { createDsImageBindings, createDsImageConfig } from '@desource/image-svelte';

  const config = createDsImageConfig({ provider: 'ipx' });
  const { dsImageAction, dsImageAttachment, dsPictureAction, dsPictureAttachment } = createDsImageBindings(config);
</script>

The returned functions no longer need a config field in every options object.

SSR prop helpers

getDsImageProps() and getDsPictureProps() generate typed native properties without mounting a component. They are useful in snippets, SSR output, and integrations:

import { getDsImageProps, getDsPictureProps } from '@desource/image-svelte';

const image = getDsImageProps({
  src: '/img/hero.jpg',
  alt: 'Hero',
  width: 800,
  format: 'webp'
});

const picture = getDsPictureProps({
  src: '/img/hero.jpg',
  alt: 'Hero',
  width: 800,
  formats: ['avif', 'webp']
});

Pass true as the second argument when the full image has already loaded and a configured placeholder should be skipped.

Responsive images, placeholders, and preloads

sizes accepts breakpoint strings such as 100vw sm:50vw lg:600px or a record. densities accepts strings, numbers, or arrays. Candidate widths are deduplicated and normalized for the selected provider.

<DsImage src="/img/hero.jpg" alt="Hero" width={1200} placeholder placeholderClass="blur" />
<DsImage src="/img/hero.jpg" alt="Hero" width={1200} placeholder={[48, 32, 25, 8]} />
<DsImage src="/img/hero.jpg" alt="Hero" width={1200} placeholder="data:image/png;base64,..." />
  • A boolean placeholder generates a small transformed image.
  • A tuple controls width, height, quality, and blur.
  • The full image replaces the placeholder only after decode succeeds.
  • placeholderClass is present only while the placeholder is visible.
  • preload inserts a responsive <link rel="preload" as="image"> into the head and reference-counts duplicate links.
  • priority sets eager loading and high fetch priority. Use preload when a head link is also required.

SSR and initial hydration output are deterministic.

Callable image helper

<script lang="ts">
  import { useDsImage } from '@desource/image-svelte';

  const $img = useDsImage();
  const hero = $img('/img/hero.jpg', { width: 800, format: 'webp', quality: 75 });
</script>

The callable helper exposes getImage, getSizes, getMeta, getAttrs, getPicture, getPreloadLink, and configured preset shortcuts.

Providers and presets

Register built-in or custom providers in the shared configuration:

<script lang="ts">
  import { cloudinaryProvider } from '@desource/image/providers/cloudinary';
  import { setDsImageConfig } from '@desource/image-svelte';

  setDsImageConfig({
    provider: 'cloudinary',
    providers: {
      cloudinary: cloudinaryProvider({ cloudName: 'demo' })
    },
    presets: {
      avatar: { width: 96, height: 96, fit: 'cover', quality: 80 }
    }
  });
</script>
<DsImage preset="avatar" src="/users/ada.jpg" alt="Ada" />

Provider modules and custom-provider utilities are documented in @desource/image.

Production deployment

The Vite plugin only supplies optimizer middleware to Vite development and preview servers. Production must use a platform image endpoint or install the IPX server adapter.

Vercel native images

Configure @sveltejs/adapter-vercel so its Build Output API contains image settings:

// svelte.config.js
import adapter from '@sveltejs/adapter-vercel';

export default {
  kit: {
    adapter: adapter({
      images: {
        sizes: [640, 768, 1024, 1280, 1536],
        domains: ['images.example.com'],
        minimumCacheTTL: 2678400,
        formats: ['image/avif', 'image/webp'],
        dangerouslyAllowSVG: false
      }
    })
  }
};

When built on Vercel, automatic detection emits /_vercel/image URLs. Keep adapter image sizes and allowed remote domains aligned with the application configuration.

SvelteKit with production IPX

Install ipx as a production dependency and add a server hook:

// src/hooks.server.ts
import { createDsImageHandle } from '@desource/image-svelte/server';

export const handle = createDsImageHandle({
  dirs: ['static'],
  domains: ['images.example.com'],
  maxAge: 60 * 60 * 24 * 30
});

createDsImageWebHandler() is available for other Fetch API servers, and createDsImageNodeMiddleware() is available for Connect/Express-style Node servers.

All IPX adapters load the optimizer lazily and only handle requests under the configured path. Remote optimization is denied by default. Add trusted domains, or set allowAllDomains: true only for an intentionally public optimizer.

License

MIT © 2026 DeSource Labs

版本与发布记录

@desource/image-svelte 共发布 6 个版本,首次发布于 2026/09/07;过去 12 个月发布了 6 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.5.0latest2026/11/0111 天前
0.4.02026/10/111 个月前
0.3.12026/10/011 个月前
0.3.02026/09/181 个月前
0.2.02026/09/151 个月前
0.1.02026/09/072 个月前

关于 @desource/image-svelte 的常见问题

@desource/image-svelte 是什么?

High-quality image optimization for Svelte and SvelteKit with responsive output, deployment-aware provider selection, dozens of built-in provider modules, and IPX.

如何安装 @desource/image-svelte?

在项目目录运行 npm install @desource/image-svelte,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:svelte(^5.29.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@desource/image-svelte 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@desource/image-svelte 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@desource/image-svelte 可以商用吗?

@desource/image-svelte 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@desource/image-svelte 的下载量有多少?

根据 npm 官方下载统计,@desource/image-svelte 在 2026/10/12 – 2026/11/10 这 30 天内被下载 17,239 次,日均约 575 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@desource/image-svelte 还在维护吗?

最新版本 0.5.0 发布于 2026/11/01(11 天前);至今共发布 6 个版本,其中过去 12 个月发布了 6 个;首次发布于 2026/09/07。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。