定义 HeadersInit 值时 WorkBox 路由中的类型错误
A type error in WorkBox routing when defining HeadersInit value
我目前正在尝试使用 TypeScript 和 WorkBox 创建一个 Service Worker。以下是我当前的 WorkBox 定义(只是为了让事情顺利进行)。我如何解决我下面解释的类型错误?
在 registerRoute
中,TypeScript 编译器告诉我们 matchPrecache
需要两个参数,另一个是 HeadersInit
类型。如果未给出,则默认为 Content-Type: text/html
。我想明确地给出类型,但是当我这样做时,我得到一个错误 matchPrecache
return value is not assignable.
如果我检查 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
现在又出现了很多消息关于 dom
和 webworker
库定义之间的类型冲突。
编辑 4 : 我注意到 https://github.com/microsoft/TypeScript/issues/20595 and consequently also 关于 TypeScript dom
和 webworker
库的冲突。从 tsconfig.json
中删除 webworker
似乎并没有解决 streamsStrategy
和 HeadersInit
的原始问题。
尝试为您的 Service Worker 创建单独的文件夹并为此文件夹扩展 main tsconfig.json。
为此,您需要使用 serviceworker.ts 创建另一个 tsconfig.json 内部文件夹,下一个内容为:
{
"extends": "../tsconfig.json",
"compilerOptions": {
"noEmit": false
},
"lib": ["webworker"],
"include": ["."]
}
而且,我希望,你知道,service worker 必须作为 webworker 编译为单独的文件。
你能为你的项目提供link吗?
我目前正在尝试使用 TypeScript 和 WorkBox 创建一个 Service Worker。以下是我当前的 WorkBox 定义(只是为了让事情顺利进行)。我如何解决我下面解释的类型错误?
在 registerRoute
中,TypeScript 编译器告诉我们 matchPrecache
需要两个参数,另一个是 HeadersInit
类型。如果未给出,则默认为 Content-Type: text/html
。我想明确地给出类型,但是当我这样做时,我得到一个错误 matchPrecache
return value is not assignable.
如果我检查 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
现在又出现了很多消息关于 dom
和 webworker
库定义之间的类型冲突。
编辑 4 : 我注意到 https://github.com/microsoft/TypeScript/issues/20595 and consequently also dom
和 webworker
库的冲突。从 tsconfig.json
中删除 webworker
似乎并没有解决 streamsStrategy
和 HeadersInit
的原始问题。
尝试为您的 Service Worker 创建单独的文件夹并为此文件夹扩展 main tsconfig.json。 为此,您需要使用 serviceworker.ts 创建另一个 tsconfig.json 内部文件夹,下一个内容为:
{
"extends": "../tsconfig.json",
"compilerOptions": {
"noEmit": false
},
"lib": ["webworker"],
"include": ["."]
}
而且,我希望,你知道,service worker 必须作为 webworker 编译为单独的文件。 你能为你的项目提供link吗?