Creating a minimal Progressive Web App (PWA) with Vite involves setting up a service worker that caches your application's assets, enabling offline functionality. Below, I'll guide you through creating a simple service worker without using any external libraries.
1. Project Structure
Assuming your Vite project has the following structure:
my-vite-app/
├── index.html
├── src/
│ ├── main.js
│ └── ... other assets
└── public/
└── service-worker.js
2. Register the Service Worker
First, you need to register the service worker in your main JavaScript file (src/main.js).
// src/main.js
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/service-worker.js')
.then(registration => {
console.log('Service Worker registered with scope:', registration.scope);
})
.catch(error => {
console.log('Service Worker registration failed:', error);
});
});
}
// Your existing Vite application code goes here
3. Create the Service Worker
Next, create the service-worker.js file in the public directory. Vite serves files in the public directory at the root (/), so the service worker will be available at /service-worker.js.
// public/service-worker.js
const CACHE_NAME = 'my-pwa-cache-v1';
const ASSETS_TO_CACHE = [
'/',
'/index.html',
'/src/main.js',
// List all other assets you want to cache, such as CSS, images, etc.
// For example:
// '/styles/main.css',
// '/images/logo.png',
];
// Install Event - Caches the assets
self.addEventListener('install', event => {
console.log('[Service Worker] Install');
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => {
console.log('[Service Worker] Caching all assets');
return cache.addAll(ASSETS_TO_CACHE);
})
);
});
// Activate Event - Cleans up old caches
self.addEventListener('activate', event => {
console.log('[Service Worker] Activate');
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cache => {
if (cache !== CACHE_NAME) {
console.log('[Service Worker] Deleting old cache:', cache);
return caches.delete(cache);
}
})
);
})
);
});
// Fetch Event - Serves cached assets when offline
self.addEventListener('fetch', event => {
console.log('[Service Worker] Fetch', event.request.url);
event.respondWith(
caches.match(event.request)
.then(cachedResponse => {
// Return cached response if found
if (cachedResponse) {
return cachedResponse;
}
// If not in cache, fetch from network
return fetch(event.request)
.then(response => {
// Optionally cache the new response
return caches.open(CACHE_NAME).then(cache => {
cache.put(event.request, response.clone());
return response;
});
})
.catch(() => {
// Fallback content if both cache and network are unavailable
if (event.request.mode === 'navigate') {
return caches.match('/index.html');
}
});
})
);
});
4. Update vite.config.js (Optional)
If you have assets that are dynamically generated or hashed by Vite, you'll need to ensure that the service worker has access to the correct file paths. However, for a minimal setup without library support, manually listing assets as shown above is sufficient. For production builds with hashed filenames, a more dynamic approach would be necessary, potentially involving build-time scripts to generate the asset list.
Here's a basic vite.config.js:
// vite.config.js
import { defineConfig } from 'vite';
export default defineConfig({
// Your Vite configuration here
base: '/', // Ensure the base is set correctly for the service worker scope
});
5. Build and Test
-
Development Server:
Vite's development server doesn't support service workers by default due to caching complexities. To test the service worker, you should build the project and serve the dist directory using a static server.
-
Build the Project:
npm run build
-
Serve the dist Directory:
You can use a simple static server like serve:
npm install -g serve
serve -s dist
-
Access Your PWA:
Open the served URL in your browser (typically http://localhost:5000) and check the console to ensure the service worker is registered. You can also test offline functionality by disabling your network and refreshing the page.
6. Additional Considerations
-
Caching Strategies: The provided service worker uses a simple cache-first strategy. Depending on your application's needs, you might want to implement more sophisticated strategies like stale-while-revalidate or network-first.
-
Asset Management: Manually listing all assets can be error-prone, especially as your project grows. Consider automating the process or using tools that integrate with build systems to generate the asset list.
-
Updates: The service worker updates when there's a change in the service-worker.js file. Ensure that the CACHE_NAME is updated appropriately to trigger the activation of the new service worker and the deletion of old caches.
-
HTTPS: Service workers require a secure context (HTTPS). Ensure your production environment serves the app over HTTPS.
Conclusion
This minimal setup provides a basic service worker that caches specified assets, enabling offline access to your Vite application. For more advanced features and optimizations, consider integrating libraries like Workbox or leveraging Vite plugins that handle PWA configurations.
Note: Always test your service worker thoroughly to ensure that caching behaves as expected and doesn't interfere with the application's dynamic functionality.