webpack效能優化之PWA
阿新 • • 發佈:2022-04-19
1.安裝外掛
workbox-webpack-plugin
並引入webpack.config.js
npm i workbox-webpack-plugin -D
const WorkboxWebpackPlugin = require('workbox-webpack-plugin'); plugins:[ new WorkboxWebpackPlugin.GenerateSW({ // pwa外掛 /** * 1幫助serviceworkbox快速啟動 * 2刪除舊的serviceworker * * 此外掛生成一個serviceworker.js配置檔案*/ clientsClaim: true, skipWaiting: true, }), ]
2.入口檔案中
註冊serviceWorker/** * 註冊serviceWorker * 處理相容性問題 * * 注意 * 1.eslint不認識window navigator全域性變數 * 需修改package.json的eslintConfig加上 * "env": { * "browser": true * } * 2.sw程式碼必須執行在伺服器上 * nodejs * serve -s dist * **/ if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker .register('/service-worker.js') .then(() => { console.log('sw註冊成功'); }) .catch(() => { console.log('sw註冊失敗'); }); }); }
3.serve -s dist 啟動 dist為打包後的資原始檔