Skip to navigation
I use vite an vuejs, how to add pwa
22.02.26
Okay, since you're using Vite and Vue.js directly (without Vue CLI), you'll need to use a different PWA plugin that's designed for Vite. The recommended plugin is **`vite-plugin-pwa`**. Here's how to add PWA support to your Vite + Vue.js project: **1. Install `vite-plugin-pwa`:** ```bash npm install vite-plugin-pwa -D # or yarn add vite-plugin-pwa -D # or pnpm add vite-plugin-pwa -D ``` **2. Configure `vite.config.js`:** Import and configure the `VitePWA` plugin in your `vite.config.js` file: ```javascript import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { VitePWA } from 'vite-plugin-pwa' export default defineConfig({ plugins: [ vue(), VitePWA({ registerType: 'autoUpdate', // or 'prompt' devOptions: { enabled: true // For testing PWA features in dev environment }, manifest: { name: 'My Awesome App', short_name: 'MyApp', description: 'My Progressive Web App description', theme_color: '#ffffff', icons: [ { src: 'pwa-192x192.png', // Path to your 192x192 icon sizes: '192x192', type: 'image/png' }, { src: 'pwa-512x512.png', // Path to your 512x512 icon sizes: '512x512', type: 'image/png', purpose: 'any maskable' } ] } }) ] }) ``` **Explanation of `vite.config.js`:** * **`import { VitePWA } from 'vite-plugin-pwa'`:** Imports the necessary function from the plugin. * **`plugins: [vue(), VitePWA({...})]`:** Adds the `VitePWA` plugin to the Vite configuration. Make sure `vue()` is also present if you're using the Vue plugin. * **`registerType: 'autoUpdate'`:** Configures the service worker registration type. `'autoUpdate'` automatically registers and updates the service worker in the background. `'prompt'` will prompt the user to update the app when a new version is available. * **`devOptions: { enabled: true }`:** Enables PWA features during development. This is helpful for testing. * **`manifest: {...}`:** Defines the Web App Manifest, which provides metadata about your PWA (name, icons, description, etc.). This is crucial for making your app installable. * **`name`:** The full name of your application. * **`short_name`:** A shorter name for use on the home screen. * **`description`:** A brief description of your application. * **`theme_color`:** The theme color for the application. * **`icons`:** An array of icon objects. You'll need to create these icons and place them in your `public` directory (or adjust the paths accordingly). The `purpose: 'any maskable'` is important for adaptive icons on Android. **3. Create PWA Icons:** Create the icons specified in the `manifest.icons` array (e.g., `pwa-192x192.png`, `pwa-512x512.png`). Place these icons in your `public` directory. You can use online tools like [Real Favicon Generator](https://realfavicongenerator.net/) to generate the necessary icons. **4. (Optional) Configure `VITE_BASE_URL` (If Needed):** If you need to use a base URL for your service worker (e.g., if your app is served from a subdirectory), you can configure `VITE_BASE_URL` in your `.env` file and access it in your service worker registration (though `vite-plugin-pwa` often handles this automatically): * **`.env` file:** ``` VITE_BASE_URL=/my-subdirectory/ # Example: If your app is in /my-subdirectory/ ``` * **Access in `vite.config.js` (if needed):** You might need to pass the `VITE_BASE_URL` to the `base` option in `vite.config.js` if you're serving your app from a subdirectory: ```javascript import { defineConfig, loadEnv } from 'vite' // Import loadEnv import vue from '@vitejs/plugin-vue' import { VitePWA } from 'vite-plugin-pwa' export default defineConfig(({ mode }) => { // Use a function to access mode const env = loadEnv(mode, process.cwd(), '') // Load env variables return { base: env.VITE_BASE_URL || '/', // Use VITE_BASE_URL or default to '/' plugins: [ vue(), VitePWA({ registerType: 'autoUpdate', devOptions: { enabled: true }, manifest: { name: 'My Awesome App', short_name: 'MyApp', description: 'My Progressive Web App description', theme_color: '#ffffff', icons: [ { src: 'pwa-192x192.png', sizes: '192x192', type: 'image/png' }, { src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png', purpose: 'any maskable' } ] } }) ] } }) ``` **Explanation:** * `import { defineConfig, loadEnv } from 'vite'` : Imports `loadEnv` to load environment variables. * `defineConfig(({ mode }) => { ... })`: Uses a function to define the configuration, allowing access to the `mode` (development or production). * `const env = loadEnv(mode, process.cwd(), '')`: Loads environment variables from `.env` files. The third argument (`''`) specifies a prefix for the environment variables to load (empty string means load all). * `base: env.VITE_BASE_URL || '/'`: Sets the `base` option to the value of `VITE_BASE_URL` if it's defined, otherwise defaults to `/`. **5. Register the Service Worker (Usually Handled by the Plugin):** `vite-plugin-pwa` automatically handles service worker registration. You typically *don't* need to manually register the service worker in your `main.js` or `App.vue` file. The plugin injects the necessary code during the build process. **6. Test Your PWA:** 1. **Build your project:** `npm run build` or `yarn build` 2. **Serve the built files:** Use a static file server to serve the contents of your `dist` directory. You can use `serve`: ```bash npm install -g serve serve dist ``` 3. **Open your browser:** Open your app in a browser that supports PWAs (Chrome, Firefox, Safari). 4. **Inspect:** Open the browser's developer tools (Application tab) and check the "Service Workers" section to see if the service worker is registered and running. 5. **Install:** If everything is configured correctly, you should see an "Install" button in your browser's address bar or menu. Click it to install your PWA. **Common Issues and Solutions:** * **Icons Not Showing:** Double-check the paths to your icons in the `manifest.icons` array. Make sure the icons exist in the `public` directory. * **Service Worker Not Registering:** Check the console for errors. Make sure the `VitePWA` plugin is correctly configured in `vite.config.js`. * **Manifest Not Found:** Verify that the `manifest.json` file is being generated correctly in your `dist` directory. * **Cache Issues:** Clear your browser's cache and unregister any existing service workers to ensure you're testing the latest version of your PWA. **Example `main.js` (Usually No Changes Needed):** You typically *don't* need to modify your `main.js` file when using `vite-plugin-pwa`. The plugin handles the service worker registration automatically. However, if you *do* need to do something custom, you can import the `registerSW` function from `vite-plugin-pwa/client` and use it to register the service worker manually: ```javascript // main.js import { createApp } from 'vue' import App from './App.vue' // import { registerSW } from 'vite-plugin-pwa' // Import if needed createApp(App).mount('#app') // Example of manual registration (usually not needed) // if ('serviceWorker' in navigator) { // registerSW({ immediate: true }) // } ``` **Key Takeaways:** * Use `vite-plugin-pwa` for PWA support in Vite + Vue.js projects. * Configure the `VitePWA` plugin in `vite.config.js` with the necessary options (especially the `manifest`). * Create the required PWA icons and place them in your `public` directory. * Test your PWA thoroughly after building and serving the files. * You generally don't need to manually register the service worker. By following these steps, you should be able to successfully add PWA support to your Vite + Vue.js project. Remember to consult the `vite-plugin-pwa` documentation for more advanced configuration options and troubleshooting tips: [https://vite-plugin-pwa.netlify.app/](https://vite-plugin-pwa.netlify.app/)
Reply
Anonymous
Information Epoch 1772051891
Design for the future, because it will be here sooner than you think.
Home
Notebook
Contact us