我目前正在尝试使用TypeScript和WorkBox创建一个服务工作人员。下面是我当前的WorkBox定义(只是为了得到一些东西)。如何解决我所解释的类型错误?
在registerRoute段TypeScript编译器中,matchPrecache需要两个参数,另一个参数为HeadersInit类型。如果未给出,则假定为默认Content-Type: text/html。我希望显式并给出类型,但是当我这样做时,我会得到一个错误-- matchPrecache返回值是不可分配的。
如果我检查strategy.d.ts,它看起来是这样的
/**
* A shortcut to create a strategy that could be dropped-in to Workbox's router.
*
* On browsers that do not support constructing new `ReadableStream`s, this
* strategy will automatically wait for all the `sourceFunctions` to complete,
* and create a final response that concatenates their values together.
*
* @param {Array<function({event, request, url, params})>} sourceFunctions
* An array of functions similar to {@link module:workbox-routing~handlerCallback}
* but that instead return a {@link module:workbox-streams.StreamSource} (or a
* Promise which resolves to one).
* @param {HeadersInit} [headersInit] If there's no `Content-Type` specified,
* `'text/html'` will be used by default.
* @return {module:workbox-routing~handlerCallback}
* @memberof module:workbox-streams
*/
declare function strategy(sourceFunctions: StreamsHandlerCallback[], headersInit: HeadersInit): RouteHandlerCallback;
export { strategy };import { clientsClaim, skipWaiting } from 'workbox-core';
import { strategy as streamsStrategy } from 'workbox-streams';
import { cleanupOutdatedCaches, matchPrecache, precacheAndRoute } from "workbox-precaching";
import { registerRoute } from "workbox-routing";
declare const self: any;
self.addEventListener("message", (event: { data: any; type: any; ports: any }) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});
precacheAndRoute(self.__WB_MANIFEST);
cleanupOutdatedCaches();
const requestHeaders: HeadersInit =
{
"Content-Type": "text/html"
}
registerRoute(
'/', streamsStrategy([() => matchPrecache("index.html")], requestHeaders)
);
skipWaiting();
clientsClaim();编辑:,好的!当我不仅看到VS代码错误,而且尝试构建时,我在命令行中发现了许多其他错误。一长段文字
node_modules/typescript/lib/lib.dom.d.ts:25:1 - error TS6200: Definitions of the following
identifiers conflict with those in another file: EventListenerOrEventListenerObject,
ImportExportKind, TableKind, ValueType,
ExportValue, Exports, ImportValue, ModuleImports,
Imports, name, ==> HeadersInit <==, BodyInit, RequestInfo, BlobPart, DOMHighResTimeStamp, CanvasImageSource, OffscreenRenderingContext, MessageEventSource,
ImageBitmapSource, OnErrorEventHandler, TimerHandler, PerformanceEntryList, ReadableStreamReadResult, VibratePattern, AlgorithmIdentifier, HashAlgorithmIdentifier, BigInteger, NamedCurve,
GLenum, GLboolean, GLbitfield, GLint, GLsizei, GLintptr, GLsizeiptr, GLuint, GLfloat, GLclampf, TexImageSource, Float32List, Int32List, GLint64, GLuint64, Uint32List, BufferSource, DOMTimeStamp,
FormDataEntryValue, IDBValidKey, Transferable, BinaryType, CanvasDirection, CanvasFillRule, CanvasLineCap, CanvasLineJoin, CanvasTextAlign, CanvasTextBaseline, ClientTypes, ColorSpaceConversion, EndingType, IDBCursorDirection, IDBRequestReadyState, IDBTransactionMode, ImageOrientation, ImageSmoothingQuality, KeyFormat, KeyType, KeyUsage, NotificationDirection, NotificationPermission, OffscreenRenderingContextId, PermissionName, PermissionState, PremultiplyAlpha, PushEncryptionKeyName, PushPermissionState, ReferrerPolicy, RequestCache, RequestCredentials, RequestDestination, RequestMode, RequestRedirect, ResizeQuality, ResponseType, ServiceWorkerState, ServiceWorkerUpdateViaCache, VisibilityState, WebGLPowerPreference, WorkerType, XMLHttpRequestResponseType我试图强调其中之一就是这个有问题的HeadersInit。我的tsconfig.json如下所示
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"noEmitOnError": true,
"lib": ["esnext", "dom"],
"strict": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"importHelpers": true,
"outDir": "out-tsc",
"sourceMap": true,
"inlineSources": true,
"forceConsistentCasingInFileNames": true,
"removeComments": true,
"rootDir": "./"
},
"include": ["**/*.ts"]
}在我的package.json里
"@types/workbox-sw": "^4.3.1",
"@types/workbox-window": "^4.3.3",所以也许这和这事有关。
编辑2:只有当我将/// <reference lib="webworker" />放在文件的顶部时,才会发生以前的错误。删除它后,我会遇到与WorkBox第2584期中描述的问题相同的问题(就错误消息而言)。
编辑3 : --我删除了显式引用,找到了WorkBox问题#2172并尝试将这个库添加到tsconfig.json中,现在又出现了许多关于dom和webworker库定义之间类型冲突的消息。
编辑4 :我注意到了https://github.com/microsoft/TypeScript/issues/20595,因此也注意到了关于TypeScript dom和webworker库冲突的TypeScript:为同一项目中的不同文件声明不同的库/引用。从webworker中删除tsconfig.json似乎不能修复streamsStrategy和HeadersInit的原始问题。
发布于 2020-08-10 08:50:23
尝试为您的服务工作人员创建单独的文件夹,并扩展此文件夹的主tsconfig.json。要做到这一点,您需要使用您的tsconfig.json在文件夹中创建另一个serviceworker.ts,并包含下一个内容:
{
"extends": "../tsconfig.json",
"compilerOptions": {
"noEmit": false
},
"lib": ["webworker"],
"include": ["."]
}而且,我希望,你知道,服务工作者必须编译成单独的文件作为网络工作者。你能提供你的项目的链接吗?
https://stackoverflow.com/questions/63310207
复制相似问题