Service Worker
Service Worker はブラウザーのバックグラウンドで動作し、キャッシュやプッシュ通知などを処理するスクリプトです。Service Worker アダプターを使うと、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 @hono/service-worker
npm i -D vitesh
yarn add hono @hono/service-worker
yarn add -D vitesh
pnpm add hono @hono/service-worker
pnpm add -D vitesh
bun add hono @hono/service-worker
bun add -D vite2. Hello World
index.html を編集します。
html
<!doctype html>
<html>
<body>
<a href="/sw">Hello World by Service Worker</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('Register Service Worker: Success')
},
function (_error) {
console.log('Register Service Worker: Error')
}
)
}
function start() {
navigator.serviceWorker
.getRegistrations()
.then(function (registrations) {
for (const registration of registrations) {
console.log('Unregister Service Worker')
registration.unregister()
}
register()
})
}
start()sw.ts で Hono アプリケーションを作成し、Service Worker アダプターの handle 関数で fetch イベントに登録します。これにより、Hono アプリケーションが /sw へのアクセスを処理できます。
ts
// To support types
// 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))fire() の使用
fire() 関数は addEventListener('fetch', handle(app)) を自動的に呼び出すため、コードが簡潔になります。
ts
import { Hono } from 'hono'
import { fire } from '@hono/service-worker'
const app = new Hono().basePath('/sw')
app.get('/', (c) => c.text('Hello World'))
fire(app)3. 実行
開発サーバーを起動します。
sh
npm run devsh
yarn devsh
pnpm run devsh
bun run dev開発サーバーはデフォルトでポート 5173 で起動します。ブラウザーで http://localhost:5173/ にアクセスして Service Worker の登録を完了し、続いて /sw にアクセスすると Hono アプリケーションのレスポンスを確認できます。