定义HeadersInit值

时间:2020-08-07 23:10:52

标签: typescript workbox

我目前正在尝试使用TypeScript和WorkBox创建Service Worker。以下是我当前的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 Code错误而且尝试构建时,我在命令行中发现了许多其他错误。一长段文字

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 issue #2584中所述的相同问题(就错误消息而言)。


编辑3:我删除了显式引用,找到了WorkBox issue #2172,并尝试将此库添加到tsconfig.json中,现在又出现了很多有关{之间的类型冲突的消息{1}}和dom库定义。


编辑4:我注意到https://github.com/microsoft/TypeScript/issues/20595,因此也TypeScript: Declare Different Libraries/References for Different Files Within the Same Project注意到TypeScript webworkerdom库冲突。从webworker中删除webworker似乎无法解决tsconfig.jsonstreamsStrategy的原始问题。

1 个答案:

答案 0 :(得分:2)

尝试为服务工作者创建单独的文件夹,并为此文件夹扩展主要tsconfig.json。 为此,您需要使用serviceworker.ts在文件夹中创建另一个tsconfig.json,其中包含下一个内容:

ReactFragment

而且,我希望您知道服务工作者必须作为Webworker进行编译以分离文件。 您可以提供项目链接吗?

相关问题