PWA缓存主应用及Yarn脚本适配问题求助(TypeScript环境)
解决方案
一、将网站主应用存入PWA缓存
1. 注册Service Worker
在主HTML文件中添加注册逻辑:
if ('serviceWorker' in navigator) { window.addEventListener('load', async () => { try { const registration = await navigator.serviceWorker.register('/sw.js'); console.log('Service Worker registered:', registration); } catch (error) { console.error('Service Worker registration failed:', error); } }); }
2. 编写Service Worker缓存逻辑(sw.js)
安装阶段缓存核心资源
定义主应用的核心文件列表,在Service Worker安装时将它们存入缓存:
const CACHE_NAME = 'main-app-cache-v1'; const CORE_ASSETS = [ '/', '/index.html', '/styles.css', '/app.js', // 添加入主应用的其他核心资源,比如图片、字体等 ]; self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME) .then((cache) => cache.addAll(CORE_ASSETS)) .then(() => self.skipWaiting()) ); });
激活阶段清理旧缓存
避免缓存冗余,激活时删除旧版本的缓存:
self.addEventListener('activate', (event) => { event.waitUntil( caches.keys().then((cacheNames) => { return Promise.all( cacheNames.filter((name) => name !== CACHE_NAME) .map((name) => caches.delete(name)) ); }).then(() => self.clients.claim()) ); });
Fetch事件拦截请求,优先使用缓存
处理资源请求,优先从缓存读取,缓存未命中时再请求网络并更新缓存:
self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request) .then((response) => { // 缓存存在则返回,否则请求网络 return response || fetch(event.request).then((networkResponse) => { // 将新的网络响应存入缓存(可选,根据需求调整) caches.open(CACHE_NAME).then((cache) => { cache.put(event.request, networkResponse.clone()); }); return networkResponse; }); }) ); });
二、TypeScript项目中确保Yarn脚本正常运行
1. 确认依赖安装
确保已安装必要的TypeScript相关依赖:
yarn add typescript ts-node @types/node --dev
2. 配置package.json脚本
根据需求添加编译、运行等脚本,示例:
{ "scripts": { "build": "tsc", // 编译TypeScript到JavaScript "dev": "ts-node src/index.ts", // 直接运行TS文件 "type-check": "tsc --noEmit", // 仅做类型检查不编译 "start": "node dist/index.js" // 运行编译后的JS文件 } }
3. 配置tsconfig.json
确保tsconfig.json的配置符合项目需求,基础示例:
{ "compilerOptions": { "target": "ES6", "module": "CommonJS", "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*"], "exclude": ["node_modules"] }
4. 常见问题排查
- 如果脚本运行时报类型错误,先执行
yarn type-check定位具体错误并修复 - 若出现依赖版本冲突,可使用
yarn list typescript查看版本,确保ts-node与typescript版本兼容 - 若编译后运行报错,检查tsconfig的outDir和rootDir是否正确,确保编译产物路径正确
内容的提问来源于stack exchange,提问作者thatsnotthepoint
相关产品推荐
相关产品推荐

