在扩展Cheerio库时,我实现了以下静态函数(其他扩展函数工作正常):
$.nodeType = function (elem: CheerioElement): number {
switch (elem.type) {
case "comment":
return Node.COMMENT_NODE; // <--- it fails here
case "tag":
return Node.ELEMENT_NODE; // <--- it fails here
case "text":
return Node.TEXT_NODE; // <--- it fails here
default:
return -1;
}
};
运行时出现以下错误(使用tsc -b
编译成功):
ReferenceError:未定义节点
Node
接口是DOM
API的一部分。因此,我realized需要在DOM
的compilerOptions
部分明确包含tsconfig.json
API。
但是,我仍然得到运行时错误。
tsconfig.json
的最小相关部分:
{
"compilerOptions": {
"baseUrl": ".",
"incremental": true,
"lib": [
"esnext",
"dom"
],
"module": "commonjs",
"noImplicitAny": true,
"outDir": "./lib/",
"sourceMap": true,
"target": "esnext",
"watch": true
},
"include": [
"./src/**/*.ts",
]
}
我想在特定的qazxsw poi文件中明确导入qazxsw poi库,其中包含该函数,但我没有找到任何“包含能力”的标准Node
lib。
包含typescript lib不会在不可用的环境中填充该功能。
虽然包含“dom”类型定义将使类型可用(在编译时),但它实际上并不使.ts
(通常由浏览器运行时提供)在运行时可用。
如果您在运行时确实需要此功能,则还需要包含node.js的DOM实现,例如DOM
,Node API此API。