gpt4 book ai didi

javascript - 使用 Vite 构建的 React.js 不包含 service-worker.ts

转载 作者:行者123 更新时间:2023-12-05 04:41:50 26 4
gpt4 key购买 nike

我正在使用 Vite 通过 React (typescript) 构建一个 SPA,并且我正在尝试注册一个 service-worker。我将脚本注册为 module 类型,service-worker.ts 位于 src/web-worker/service-worker.ts。在 src/web-worker

也有一个 tsconfig.json

在 Dev 中一切正常,但在构建时,src/web-worker/service-worker.ts 不会被替换为任何等效内容

有什么建议吗?

index.html

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/src/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="/src/styles/globals.css">
<title>Vite App</title>
</head>

<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
<script type="text/javascript">
if ('serviceWorker' in navigator) {
(async () => {
await navigator.serviceWorker.register("src/web-worker/service-worker.ts", { type: 'module' })
console.log("Service worker registered")
})()
}
</script>
</body>

</html>

src/web-worker/service-worker.ts

// Constants
const CACHE_NAME = 'mycache-v1.0.0'
const urlsToCache = ['/']

declare const self: ServiceWorkerGlobalScope;

self.addEventListener('install', async (event: ExtendableEvent) => {
try {
// Create (open) cache
const cache = await caches.open(CACHE_NAME)
await cache.addAll(urlsToCache)
console.log("Cache opened")
} catch (err: any) {
console.log("Error while installing SW: ", err.message)
}
})

self.addEventListener('fetch', (e: FetchEvent) => {
e.respondWith((async () => {
// Handling fetch
console.log(`Handling req for '${e.request.url}'`)
const cachedRes = await caches.match(e.request, { cacheName: CACHE_NAME })
if (cachedRes) {
console.log(`Serving cached response for '${e.request.url}'`)
}
return cachedRes || await fetch(e.request)
})())
})

export default null

src/web-worker/tsconfig.json

{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["ESNext", "WebWorker"],
"allowJs": false,
"skipLibCheck": false,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
},
"include": ["*.ts"]
}

最佳答案

这个https://github.com/antfu/vite-plugin-pwa有一个vitejs插件.您可以在此处找到 React 文档 https://vite-plugin-pwa.netlify.app/examples/react.html

关于javascript - 使用 Vite 构建的 React.js 不包含 service-worker.ts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69961761/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com