问题
I have a project that is written in TypeScript. I use both the dom and Web Workers, so I need the webworker.d.ts library in some files and dom.d.ts in other files.
I already tried adding "webworker" to the lib option in tsconfig.json, but those two are incompatible.
Another thing I tried is adding:
/// <reference no-default-lib="true"/>
/// <reference lib="esnext" />
/// <reference lib="webworker" />
at the top of my service worker file, but "webworker" is applied to every file instead of just the one that includes the references.
How can I have both files that need references to dom and files that need references to webworker within the same project?
Here is my config:
// 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"]
}
回答1:
With vue see Microsoft/TypeScript/issues/20595 which states:
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.
Try like:
const ctx: Worker = self as any;
ctx.postMessage();
OR: Follow the linked 20595 recipe which will require typesetting to some webworker parts or making types files for components you need/use.
Use:
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;
}
})();
Then reference by, for example:
import globalObject from 'globalObject'
globalObject.postMessage({});
来源:https://stackoverflow.com/questions/54188827/typescript-declare-different-libraries-references-for-different-files-within-th