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
npm i -D vite
sh
yarn add hono
yarn add -D vite
sh
pnpm add hono
pnpm add -D vite
sh
bun add hono
bun add -D vite
2. 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))
3. 執行
啟動開發伺服器。
sh
npm run dev
sh
yarn dev
sh
pnpm run dev
sh
bun run dev
預設情況下,開發伺服器將在 5173
連接埠上執行。在您的瀏覽器中存取 https://127.0.0.1:5173/
以完成 Service Worker 註冊。然後,存取 /sw
以查看來自 Hono 應用程式的回應。