我有一个用TypeScript编写的项目。我同时使用dom和Web Workers,因此在某些文件中需要webworker.d.ts库,在其他文件中需要dom.d.ts。
我已经尝试在tsconfig.json的lib选项中添加“ webworker”,但是这两个是不兼容的。
我尝试添加的另一件事:
/// <reference no-default-lib="true"/>
/// <reference lib="esnext" />
/// <reference lib="webworker" />
位于我的服务工作者文件的顶部,但是“ webworker”将应用于每个文件,而不仅仅是包含引用的文件。
在同一个项目中,如何既需要引用dom的文件又需要引用webworker的文件?
这是我的配置:
// tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"noEmitHelpers": false,
"moduleResolution": "node",
"experimentalDecorators": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"types": ["webpack-env"],
"paths": {
"@/*": ["src/*"]
},
"lib": ["esnext", "dom", "dom.iterable", "scripthost"]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": ["node_modules"]
}
答案 0 :(得分:1)
有关vue,请参见Microsoft/TypeScript/issues/20595,其中指出:
We have found that what is meaningful in the global scope of a web worker is significantly more narrow than we find out of the DOM. So we tend to author with "lib": [ "dom" ] and then just declare the handful of APIs we require to make a web worker work, or we obtain a reference to the global object, treat it as any, and pick off certain properties from the global scope and type them at the point where we pick them off.
尝试:
const ctx: Worker = self as any;
ctx.postMessage();
或:按照linked 20595食谱,这将需要对某些Webworker部件进行排版或为您需要/使用的组件制作类型文件。
使用:
const globalObject: any = (function (): any {
if (typeof global !== 'undefined') {
// global spec defines a reference to the global object called 'global'
// https://github.com/tc39/proposal-global
// `global` is also defined in NodeJS
return global;
}
else if (typeof window !== 'undefined') {
// window is defined in browsers
return window;
}
else if (typeof self !== 'undefined') {
// self is defined in WebWorkers
return self;
}
})();
然后引用,例如:
import globalObject from 'globalObject'
globalObject.postMessage({});