서비스 워커
서비스 워커는 브라우저의 백그라운드에서 실행되는 스크립트로, 캐싱이나 푸시 알림과 같은 작업을 처리한다. 서비스 워커 어댑터를 사용하면 Hono로 만든 애플리케이션을 브라우저 내에서 FetchEvent 핸들러로 실행할 수 있다.
이 페이지에서는 Vite를 사용해 프로젝트를 생성하는 예제를 보여준다.
1. 설정
먼저 프로젝트 디렉토리를 생성하고 이동한다:
sh
mkdir my-app
cd my-app프로젝트에 필요한 파일을 생성한다. package.json 파일을 다음과 같이 만든다:
json
{
"name": "my-app",
"private": true,
"scripts": {
"dev": "vite dev"
},
"type": "module"
}마찬가지로 tsconfig.json 파일을 다음과 같이 생성한다:
json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"lib": ["ES2020", "DOM", "WebWorker"],
"moduleResolution": "bundler"
},
"include": ["./"],
"exclude": ["node_modules"]
}다음으로 필요한 모듈을 설치한다.
sh
npm i hono
npm i -D vitesh
yarn add hono
yarn add -D vitesh
pnpm add hono
pnpm add -D vitesh
bun add hono
bun add -D vite2. Hello World
index.html을 수정한다:
html
<!doctype html>
<html>
<body>
<a href="/sw">Service Worker로 Hello World</a>
<script type="module" src="/main.ts"></script>
</body>
</html>main.ts는 Service Worker를 등록하는 스크립트다:
ts
function register() {
navigator.serviceWorker
.register('/sw.ts', { scope: '/sw', type: 'module' })
.then(
function (_registration) {
console.log('Service Worker 등록: 성공')
},
function (_error) {
console.log('Service Worker 등록: 오류')
}
)
}
function start() {
navigator.serviceWorker
.getRegistrations()
.then(function (registrations) {
for (const registration of registrations) {
console.log('Service Worker 등록 해제')
registration.unregister()
}
register()
})
}
start()sw.ts에서 Hono를 사용해 애플리케이션을 생성하고, Service Worker 어댑터의 handle 함수를 통해 fetch 이벤트에 등록한다. 이를 통해 Hono 애플리케이션이 /sw에 대한 접근을 가로챌 수 있다.
ts
// 타입 지원을 위해
// https://github.com/microsoft/TypeScript/issues/14877
declare const self: ServiceWorkerGlobalScope
import { Hono } from 'hono'
import { handle } from 'hono/service-worker'
const app = new Hono().basePath('/sw')
app.get('/', (c) => c.text('Hello World'))
self.addEventListener('fetch', handle(app))3. 실행하기
개발 서버를 시작한다.
sh
npm run devsh
yarn devsh
pnpm run devsh
bun run dev기본적으로 개발 서버는 5173 포트에서 실행된다. 브라우저에서 http://localhost:5173/에 접속해 Service Worker 등록을 완료한다. 그런 다음 /sw에 접속해 Hono 애플리케이션의 응답을 확인한다.