시작하기
설치
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.
설치
설치플러그인을 설치하기 위해 AI-Assisted Setup을 사용할 수 있습니다. 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 { 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, },}); bypass cdnUrl if 절을 건너뛸 수 있습니다 bind, src절대 URL을 전달할 경우 resolve.
const src = await AssetCache.src('https://cdn.example.com/assets/videos/intro.mp4');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에 해결됩니다.
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에 아직 존재하는 cached assets를 반환합니다. |
getCacheSize | cached bytes의 총량을 반환합니다. |
remove | key 또는 URL로 하나의 cached asset를 삭제합니다. |
clear | plugin이 관리하는 모든 cached asset를 삭제합니다. |
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