[英]How To Add Service Worker In React Project
我想在我的React項目中添加Service Worker。 項目已准備就緒,默認服務似乎無法正常工作。
即使當我嘗試導入它時,它也會出現此錯誤:
嘗試導入錯誤:“ ./ registerServiceWorker”不包含默認導出(導入為“ registerServiceWorker”)。
此外,如何在默認版本的serviceWorker文件中添加要緩存的文件。
如果我像無反應(框架)應用程序一樣添加自己的自定義serviceWorker文件,它將適用於反應情況嗎?
目前,我的index.js中有這些代碼
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { BrowserRouter } from 'react-router-dom'
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root'));
registerServiceWorker();
並且這樣說:“嘗試導入錯誤:'./ registerServiceWorker'不包含默認導出(導入為'registerServiceWorker')。”
我正在使用的Service Worker如下:(React的默認代碼)
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more,
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See /CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
根據您的錯誤信息,registerServiceWorker.js文件存在問題。
import registerServiceWorker from './registerServiceWorker';
但是,registerServiceWorker.js文件中沒有以下內容
export registerServiceWorker
因此,我建議將以下內容添加到registerServiceWorker.js
export default registerServiceWorker
用這個來導入js文件
import * as registerServiceWorker from './registerServiceWorker';
並像這樣使用它:
registerServiceWorker.unregister();
我認為您對導入/導出有一些誤解,因此我將在此進行解釋。
如果我們想將某個文件(例如child.js)導入另一個文件(例如parent.js)。在child.js之類的文件中,必須進行導出。
有一些方法可以做到這一點。 1.在Child.js中
const child = () => {
}
export default Child
我們可以像下面這樣將其導入parent.js中,使用默認表達式,我們實際上可以在下面的Child位置使用任何名稱(通常保持不變)。
import Child from './child.js'
import ChildReplace from './child.js' //This also works, the ChildReplace are actually the Child in the child.js
您可能會看到另一種導入方式,例如:
從'./registerServiceWorker'導入*作為registerServiceWorker;
*表示registerServiceWorker.js。“ as registerServiceWorker”中的所有內容都為所有內容命名,以便我們輕松導入。
導入文件的方法,因為在registerServiceWorker.js中,有許多導出表達式,但是沒有導出默認值。
您可以使用導入從registerServiceWorker.js文件導出的所有功能
從'./registerServiceWorker'導入*作為registerServiceWorker;
然后,您可以從該文件調用任何方法到index.js文件,例如-
registerServiceWorker.unregister();
嘗試這個。
create-react-app FolderName
只是自動為您的應用程序創建一個registerServiceWorker
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.