시작하기
설치
Set up this Capacitor plugin in the project.
Use the package manager already used by the project.
Install these package(s): `@capgo/capacitor-asset-cache`
Run the required Capacitor sync/update step after installation.
Read this markdown guide for the full setup steps: https://raw.githubusercontent.com/Cap-go/website/refs/heads/main/apps/docs/src/content/docs/docs/plugins/asset-cache/getting-started.mdx
Use that guide for platform-specific steps, native file edits, permissions, config changes, imports, and usage setup.
If that guide references other docs pages, read them too.
설치
설치Capgo의 AI-assisted 설정을 사용하여 플러그인을 설치할 수 있습니다. AI 도구에 Capgo 기능을 추가하려면 다음 명령어를 사용하세요:
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins다음 명령어를 사용하세요:
Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/capacitor-asset-cache` plugin in my project.만약 Manual Setup을 선호한다면, 플러그인을 설치하려면 다음 명령어를 실행하세요:
npm install @capgo/capacitor-asset-cachenpx cap syncimport
Section titled “Import”import { AssetCache } from '@capgo/capacitor-asset-cache';CDN을 설정하세요
Section titled “CDN을 설정하세요”앱이 시작될 때 CDN의 기본 URL을 한 번만 설정하세요. 상대 경로의 자산 경로는 이 URL에 상대적입니다.
AssetCache.configure({ cdnUrl: 'https://cdn.example.com/assets/', revalidate: { strategy: 'ttl', maxAgeSeconds: 86400, },}); Skip할 수 있습니다 cdnUrl 만약 절대 URL을 전달한다면 bind, src또는 resolve.
const src = await AssetCache.src('https://cdn.example.com/assets/videos/intro.mp4');이미지나 비디오를 바인딩하세요
Section titled “이미지나 비디오를 바인딩하세요”bind 은 가장 투명한 표시 경로입니다. 이 요소를 로딩 중으로 표시하고, 로컬 파일이 준비되면 로컬 소스 URL을 할당합니다.
const image = document.querySelector<HTMLImageElement>('#hero');
if (image) { const binding = AssetCache.bind(image, 'images/hero.jpg'); await binding.promise;}<img id="hero" alt="Product preview" />img[data-asset-cache-state='loading'],video[data-asset-cache-state='loading'] { opacity: 0.45;}
img[data-asset-cache-state='ready'],video[data-asset-cache-state='ready'] { opacity: 1;}리액트
리액트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, 'images/hero.jpg'); return () => binding.cancel(); }, []);
return <img ref={imageRef} alt="Product preview" />;}뷰
뷰<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, 'images/hero.jpg', { cdnUrl: 'https://cdn.example.com/assets/', }); }});
onUnmounted(() => binding?.cancel());</script>
<template> <img ref="image" alt="Product preview" /></template>프레임워크 상태 직접 소스
프레임워크 상태 직접 소스사용 src 프레임워크가 로딩 및 오류 상태를 제어할 때 사용하세요. 로컬 파일이 존재하는 후에만 로컬 소스 문자열이 promise에 resolve됩니다.
const src = await AssetCache.src('videos/intro.mp4');
videoElement.src = src;사용 resolve 또한 메타데이터가 필요할 때 사용하세요:
const source = await AssetCache.resolve('images/hero.jpg');
console.log(source.src, source.local, source.fromCache, source.status);보호된 자산
프레임워크 상태 직접 소스원본 fetch에 헤더를 전달하세요. 이 기능은 서명된 CDN 경로, 인증된 미디어 또는 단기 토큰에 유용합니다.
const src = await AssetCache.src('private/videos/intro.mp4', { cdnUrl: 'https://cdn.example.com/assets/', headers: { Authorization: `Bearer ${token}`, },});플러그인은 원격 파일을 가져오거나 재검증하는 동안 헤더를 사용합니다. 이미지 또는 비디오 태그는 플러그인이 반환한 로컬 소스 URL만 받습니다.
재검증
재검증기본 전략을 설정하여 configure 또는 한 개의 자산에 대해 재정의합니다.
await AssetCache.src('videos/intro.mp4', { revalidate: { strategy: 'etag', },});사용 가능한 전략:
| 전략 | 사용할 때 |
|---|---|
never | 캐시된 로컬 파일이 충분할 때까지 명시적으로 제거하지 않는 한. |
ttl | 단순한 신선도 창구가 필요할 때. |
always | 이 플러그인은 원격 자산을 매번 확인하도록 하려면. |
etag | CDN은 안정적인 ETag 헤더를 반환합니다. |
last-modified | CDN은 신뢰할 수 있는 Last-Modified 헤더를 반환합니다. |
저장 및 개인 정보 보호
저장 및 개인 정보 보호- iOS는 파일을 Application Support 하위 디렉토리에 저장하고 iCloud 백업에서 캐시 루트를 제외합니다.
- Android는 앱 내부 파일 디렉토리에 파일을 저장합니다.
- 웹은 브라우저 캐시 API와 localStorage 메타데이터를 개발자용 fallback으로 사용합니다.
- 캐시된 파일은 앱 샌드박스 내부에 숨겨져 있으며 사용자 미디어에 저장되지 않습니다.
- 캐시된 파일은 삭제되며, 앱 데이터를 지우거나 플러그인을 제거하면 삭제됩니다.
clear()또는remove().
캐시는 지속되지만, 보안 경계는 아닙니다. 장치가 위협받은 경우에만 읽을 수 없는 자산을 암호화하여 제공해야 합니다.
고급 캐시 제어
고급 캐시 제어 섹션대부분의 UI code는 bind, src또는 resolve. 명시적인 캐시 관리가 필요할 때 이 헬퍼를 사용하세요:
| 메서드 | 설명 |
|---|---|
get | remote URL을 native file metadata로 변환합니다. |
list | disk에 여전히 존재하는 캐시된 자산을 반환합니다. |
getCacheSize | 총 캐시 바이트 수를 반환합니다. |
remove | key 또는 URL로 하나의 캐시된 자산을 삭제합니다. |
clear | 플러그인이 관리하는 모든 캐시된 자산을 삭제합니다. |
const asset = await AssetCache.get({ url: 'https://cdn.example.com/assets/videos/intro.mp4', key: 'videos/intro.mp4', revalidate: { strategy: 'last-modified' },});- GitHub: https://github.com/Cap-go/capacitor-asset-cache/
- 패키지:
@capgo/capacitor-asset-cache