我正在使用Create React App实用程序创建React App,并且我想覆盖它提供的默认服务工作程序。
由于我不想退出应用程序,因此我使用workbox-build
软件包来创建我的服务工作者(我也使用yarn安装了workbox-sw
软件包)。
我的服务工作者代码如下:
/* eslint-disable no-restricted-globals */
import * as core from 'workbox-core';
import * as routing from 'workbox-routing';
import * as strategies from 'workbox-strategies';
import * as precaching from 'workbox-precaching';
self.addEventListener('message', event => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
core.clientsClaim();
routing.registerRoute(
new RegExp('^https://fonts.googleapis.com'),
new strategies.StaleWhileRevalidate({
cacheName: 'google-fonts-stylesheets-v1',
})
);
precaching.precacheAndRoute([]);
routing.registerNavigationRoute(
precaching.getCacheKeyForURL('/index.html'), {
blacklist: [/^\/_/, /\/[^/?]+\.[^/]+$/],
}
);
我的workbox-build
脚本是:
const workboxBuild = require('workbox-build');
// NOTE: This should be run *AFTER* all your assets are built
const buildSW = () => {
// This will return a Promise
return workboxBuild.injectManifest({
swSrc: 'src/service-worker.js',
swDest: 'build/service-worker.js',
globDirectory: 'build',
globPatterns: [
'**\/*.{js,css,html,png,json}',
]
}).then(({
count,
size,
warnings
}) => {
// Optionally, log any warnings and details.
warnings.forEach(console.warn);
console.log(`${count} files will be precached, totaling ${size} bytes.`);
});
}
buildSW();
我正在使用的用于注册服务工作者的信息:
import { Workbox } from 'workbox-window';
export function register() {
if ('serviceWorker' in navigator) {
const wb = new Workbox('/service-worker.js');
wb.register();
}
}
但是,当我运行我的应用程序时,出现以下错误:
service-worker.js:2 Uncaught SyntaxError: Cannot use import statement outside a module
:3000/107/aggregator:1 Uncaught (in promise) TypeError: Failed to register a ServiceWorker for scope ('http://localhost:3000/') with script ('http://localhost:3000/service-worker.js'): ServiceWorker script evaluation failed
我在做什么错了?
答案 0 :(得分:3)
工作者中还没有模块支持。
importScripts()可以为您完成这项工作,但无法导入模块,这意味着其中包含“ export” 关键字的任何内容。
https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts