@capgo/capacitor-asset-cache

中文文档
8.1.8发布于 2026/10/15MPL-2.0TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 4万

Capacitor plugin for transparent local caching of large images and videos.

原始使用文档
文档目录27 节
  1. ➡️ Get started for free
  2. Key features
  3. Why Asset Cache?
  4. Documentation
  5. Compatibility
  6. Install
  7. Usage
  8. React
  9. Vue
  10. Direct Source
  11. Protected Assets
  12. Inspect the Resolution
  13. Advanced Cache Control
  14. Platform notes
  15. API
  16. configure(...)
  17. resolve(...)
  18. src(...)
  19. bind(...)
  20. get(...)
  21. remove(...)
  22. clear()
  23. list()
  24. getCacheSize()
  25. getPluginVersion()
  26. Interfaces
  27. Type Aliases

@capgo/capacitor-asset-cache

Cache large images, videos and other CDN files on the device so they load instantly and work offline. One call turns a remote URL into a local file your WebView can display.

Capgo - Build Capacitor apps with AI, ship updates instantly

Capgo: push fixes to your Capacitor users in minutes, build signed iOS and Android apps without a Mac, and roll back in one click.

➡️ Get started for free

14-day unlimited free trial. No credit card required

🤖 Building with an AI coding agent? Install Capgo skills so Claude Code, Codex, Cursor, Copilot, or Gemini CLI know how to install and use @capgo/capacitor-asset-cache in your Capacitor app: npx skills add Cap-go/capgo-skills. Then ask your agent: "Add @capgo/capacitor-asset-cache to my Capacitor app and wire it up." Agent setup guides · Hosted MCP

@capgo/capacitor-asset-cache for Capacitor apps

Key features

  • Local files: get() downloads an asset once and returns a persistent local file.
  • Display ready: resolve() and src() turn a CDN path or URL into a value you can put in src.
  • Revalidation: never, ttl (with maxAgeSeconds), always, etag or last-modified strategies, plus custom request headers.
  • Cache management: list(), getCacheSize(), remove() and clear().
  • Platforms: iOS, Android and Web. The web implementation keeps the same API in the browser.

Why Asset Cache?

@capgo/capacitor-asset-cache lets app code ask for a media source and bind it directly to an <img>, <video>, React component, Vue template, or any other web UI.

  • Pass a CDN path like videos/intro.mp4 and get a local display-ready URL back.
  • Uses persistent app storage: iOS Application Support and Android internal files.
  • src(...) and resolve(...) only resolve after a local file exists; if the plugin cannot create a local file, the call rejects.
  • bind(...) updates an image or video element from loading to ready when the local file is available.
  • Supports cache-only, TTL, ETag, Last-Modified, and always-revalidate modes.
  • Keeps lower-level get, list, remove, and clear helpers for advanced cache management.

The cache is removed when the app is uninstalled, but it is not stored in the platform cache directory that the system may flush under pressure.

Documentation

The most complete doc is available here: https://capgo.app/docs/plugins/asset-cache/

Compatibility

Plugin versionCapacitor compatibilityMaintained
v8.*.*v8.*.*Yes
v7.*.*v7.*.*On demand

Install

npm install @capgo/capacitor-asset-cache
npx cap sync

Usage

Configure the CDN once, then bind media elements to CDN paths. The element only receives the local webview URL after the native fetch is done.

import { AssetCache } from '@capgo/capacitor-asset-cache';

AssetCache.configure({
  cdnUrl: 'https://cdn.example.com/assets/',
  revalidate: {
    strategy: 'ttl',
    maxAgeSeconds: 86400,
  },
});

const video = document.querySelector('video');
if (video) {
  AssetCache.bind(video, 'videos/intro.mp4');
}
video[data-asset-cache-state='loading'],
img[data-asset-cache-state='loading'] {
  opacity: 0.4;
}

video[data-asset-cache-state='ready'],
img[data-asset-cache-state='ready'] {
  opacity: 1;
}

React

import { useEffect, useRef } from 'react';
import { AssetCache } from '@capgo/capacitor-asset-cache';

AssetCache.configure({ cdnUrl: 'https://cdn.example.com/assets/' });

export function HeroImage() {
  const imageRef = useRef<HTMLImageElement>(null);

  useEffect(() => {
    if (!imageRef.current) return;

    const binding = AssetCache.bind(imageRef.current, 'hero.jpg');
    return () => binding.cancel();
  }, []);

  return <img ref={imageRef} alt="" />;
}

Vue

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
import { AssetCache, type AssetCacheBinding } from '@capgo/capacitor-asset-cache';

const image = ref<HTMLImageElement | null>(null);
let binding: AssetCacheBinding | undefined;

onMounted(() => {
  if (image.value) {
    binding = AssetCache.bind(image.value, 'hero.jpg', {
      cdnUrl: 'https://cdn.example.com/assets/',
    });
  }
});

onUnmounted(() => binding?.cancel());
</script>

<template>
  <img ref="image" alt="" />
</template>

Direct Source

Use src(...) when your framework already manages loading state. It resolves only after the local file is ready.

const src = await AssetCache.src('images/hero.jpg');

Protected Assets

Pass headers to the native fetch. The web element receives only the local file URL returned by the plugin.

const src = await AssetCache.src('private/videos/intro.mp4', {
  cdnUrl: 'https://cdn.example.com/assets/',
  headers: {
    Authorization: `Bearer ${token}`,
  },
});

Inspect the Resolution

Use resolve(...) when you also want metadata about the local file resolution.

const source = await AssetCache.resolve('images/hero.jpg');

console.log(source.src, source.fromCache, source.status);

Advanced Cache Control

Use get(...) directly only when you need the raw native file metadata.

const asset = await AssetCache.get({
  url: 'https://example.com/videos/intro.mp4',
  key: 'intro.mp4',
  revalidate: { strategy: 'etag' },
});

Platform notes

  • iOS stores files under Application Support and excludes the cache root from iCloud backup.
  • Android stores files under the app internal files directory.
  • Web uses the browser Cache API and localStorage metadata as a development fallback.

API

Persistent asset cache for large Capacitor images, videos, and other media.

configure(...)

configure(options: AssetCacheConfigOptions) => void

Set defaults for future src(...), resolve(...), and bind(...) calls.

ParamType
optionsAssetCacheConfigOptions

resolve(...)

resolve(path: AssetCacheSourceInput, options?: AssetCacheSourceOptions | undefined) => Promise<ResolvedAssetSource>

Resolve a CDN path or remote URL into a local display-ready source URL.

ParamType
pathAssetCacheSourceInput
optionsAssetCacheSourceOptions

Returns: Promise<ResolvedAssetSource>


src(...)

src(path: AssetCacheSourceInput, options?: AssetCacheSourceOptions | undefined) => Promise<string>

Resolve a CDN path or remote URL into a local string ready for img.src or video.src.

ParamType
pathAssetCacheSourceInput
optionsAssetCacheSourceOptions

Returns: Promise<string>


bind(...)

bind(element: AssetCacheBindableElement, path: AssetCacheSourceInput, options?: AssetCacheBindOptions | undefined) => AssetCacheBinding

Bind an image or video element to a local asset and update it when ready.

ParamType
elementany
pathAssetCacheSourceInput
optionsAssetCacheBindOptions

Returns: AssetCacheBinding


get(...)

get(options: GetAssetOptions) => Promise<CachedAsset>

Resolve an asset URL into a local persistent file.

ParamType
optionsGetAssetOptions

Returns: Promise<CachedAsset>


remove(...)

remove(options: AssetCacheKeyOptions) => Promise<RemoveAssetResult>

Remove one cached asset by key or URL.

ParamType
optionsAssetCacheKeyOptions

Returns: Promise<RemoveAssetResult>


clear()

clear() => Promise<ClearCacheResult>

Remove every cached asset managed by this plugin.

Returns: Promise<ClearCacheResult>


list()

list() => Promise<AssetCacheListResult>

List cached assets that still exist on disk.

Returns: Promise<AssetCacheListResult>


getCacheSize()

getCacheSize() => Promise<AssetCacheSizeResult>

Return total cached asset bytes.

Returns: Promise<AssetCacheSizeResult>


getPluginVersion()

getPluginVersion() => Promise<PluginVersionResult>

Returns the platform implementation version marker.

Returns: Promise<PluginVersionResult>


Interfaces

AssetCacheConfigOptions

Shared defaults used by AssetCache.src(...) and AssetCache.resolve(...).

PropTypeDescription
cdnUrlstringBase CDN URL used when path is relative.
revalidateAssetCacheRevalidateOptionsDefault revalidation behavior for resolved assets.

AssetCacheRevalidateOptions

Revalidation options for cached assets.

PropTypeDescriptionDefault
strategyAssetCacheRevalidateStrategynever returns the local file when present. ttl re-downloads after maxAgeSeconds. always revalidates on every call and sends known validators. etag and last-modified use the matching HTTP validator when present.'never'
maxAgeSecondsnumberFreshness window in seconds for the ttl strategy.

ResolvedAssetSource

Result returned by AssetCache.resolve(...).

PropTypeDescription
srcstringLocal URL ready to assign to HTMLImageElement.src, HTMLVideoElement.src, or framework bindings.
pathstringOriginal path passed by the caller.
remoteUrlstringFully resolved remote URL used by the native fetch.
keystringStable cache key used when one is known.
localtrueAlways true for successful resolve(...) calls.
fromCachebooleanTrue when the persistent local copy already existed before this call.
status'hit' | 'downloaded' | 'notModified'Result of the local source resolution.
assetCachedAssetNative cached asset payload for the local file.

CachedAsset

A cached asset stored in app-owned persistent storage.

PropTypeDescription
keystringStable cache key used by the plugin.
urlstringOriginal remote URL.
pathstringAbsolute native filesystem path.
uristringFile URI that can be passed to Capacitor.convertFileSrc.
mimeTypestringBest known MIME type from the HTTP response.
etagstringLast known HTTP ETag validator.
lastModifiedstringLast known HTTP Last-Modified validator.
sizenumberFile size in bytes.
updatedAtnumberUnix timestamp in milliseconds for the last successful download.
checkedAtnumberUnix timestamp in milliseconds for the last cache check.
fromCachebooleanTrue when the returned asset came from local persistent storage.
status'hit' | 'downloaded' | 'notModified'Result of the cache lookup.

ResolveAssetSourceOptions

Input used by AssetCache.src(...) and AssetCache.resolve(...).

PropTypeDescription
pathstringCDN-relative path or absolute remote URL for an image, video, or other media asset.

AssetCacheSourceOptions

Per-asset options used by AssetCache.src(...) and AssetCache.resolve(...).

PropTypeDescription
keystringStable cache key. Include a file extension when the URL path does not have one.
headers{ [key: string]: string; }HTTP headers sent while fetching or revalidating the asset.

AssetCacheBinding

Binding returned by AssetCache.bind(...).

PropTypeDescription
promisePromise<ResolvedAssetSource>Resolves with the local source metadata after the element is updated.
MethodSignatureDescription
cancel() => voidPrevents this binding from updating the element after it resolves.

AssetCacheBindOptions

Options used by AssetCache.bind(...).

PropTypeDescriptionDefault
stateAttributestringAttribute updated with loading, ready, or error.'data-asset-cache-state'
loadingClassstringClass added while the local file is being fetched.
readyClassstringClass added after the local file is assigned to the element.
errorClassstringClass added when local resolution fails.

GetAssetOptions

Options used to resolve a remote asset into a local persistent file.

PropTypeDescription
urlstringRemote asset URL.
keystringStable cache key. If omitted, the plugin uses a SHA-256 hash of url. Include a file extension when the asset will be used directly in an &lt;img&gt; or &lt;video&gt; tag.
headers{ [key: string]: string; }HTTP headers sent while fetching or revalidating the asset.
revalidateAssetCacheRevalidateOptionsControls when an existing persistent file should be checked again.

RemoveAssetResult

Remove result.

PropTypeDescription
removedbooleanTrue when a cached file or its metadata was removed.

AssetCacheKeyOptions

Identifies an asset by cache key or by URL. key wins when both are set.

PropTypeDescription
keystringStable cache key.
urlstringRemote asset URL used to derive the default key.

ClearCacheResult

Clear result.

PropTypeDescription
removednumberNumber of cached assets removed.

AssetCacheListResult

List result.

PropTypeDescription
assetsCachedAsset[]Cached assets that still have files on disk.

AssetCacheSizeResult

Cache size result.

PropTypeDescription
sizenumberTotal cached asset size in bytes.

PluginVersionResult

Plugin version payload.

PropTypeDescription
versionstringVersion identifier returned by the platform implementation.

Type Aliases

AssetCacheRevalidateStrategy

Revalidation mode used when an asset already exists in persistent storage.

'never' | 'ttl' | 'always' | 'etag' | 'last-modified'

AssetCacheSourceInput

Convenience input accepted by AssetCache.src(...) and AssetCache.resolve(...).

string | ResolveAssetSourceOptions

AssetCacheBindableElement

Element supported by AssetCache.bind(...).

HTMLImageElement | HTMLVideoElement

版本与发布记录

@capgo/capacitor-asset-cache 共发布 9 个版本,首次发布于 2026/06/27;过去 12 个月发布了 9 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
8.1.8latest2026/10/1525 天前
8.1.72026/10/1327 天前
8.1.62026/10/091 个月前
8.1.52026/10/081 个月前
8.1.42026/10/081 个月前
8.1.32026/09/161 个月前

关于 @capgo/capacitor-asset-cache 的常见问题

@capgo/capacitor-asset-cache 是什么?

Capacitor plugin for transparent local caching of large images and videos.

如何安装 @capgo/capacitor-asset-cache?

在项目目录运行 npm install @capgo/capacitor-asset-cache,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@capacitor/core(>=8.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@capgo/capacitor-asset-cache 支持 TypeScript 吗?

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

@capgo/capacitor-asset-cache 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@capgo/capacitor-asset-cache 可以商用吗?

@capgo/capacitor-asset-cache 使用 MPL-2.0 许可。弱 Copyleft:可以商用,也可以和闭源代码一起使用;但如果分发时修改了 MPL 授权的文件,这些文件的修改需以 MPL 开源。以上为概括,不构成法律意见,请以许可原文为准。

@capgo/capacitor-asset-cache 的下载量有多少?

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

@capgo/capacitor-asset-cache 还在维护吗?

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