[英]Typescript cannot find name window or document
For either case:对于任何一种情况:
document.getElementById('body');
// or
window.document.getElementById('body');
I get error TS2304: Cannot find name 'window'.
我收到error TS2304: Cannot find name 'window'.
Am I missing something in tsconfig.json
for a definition file I should install?我是否在tsconfig.json
中遗漏了一些我应该安装的定义文件?
I get the message when running tsc
and in vscode
我在运行tsc
和vscode
时收到消息
tsconfig.json: tsconfig.json:
{
"compilerOptions": {
"allowJs": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"jsx": "react",
"module": "commonjs",
"moduleResolution": "node",
"noEmitOnError": true,
"noImplicitAny": false,
"sourceMap": true,
"suppressImplicitAnyIndexErrors": true,
"target": "ES2016",
"typeRoots": [
"node_modules/@types/",
"typings/index.d.ts"
]
},
"exclude": [
"node_modules",
"**/*-aot.ts"
]
}
My Answer: For use with tsconfig.json
I target es5
and use lib: ["es2015", "dom"]
我的答案:为了与tsconfig.json
使用,我以es5
为目标并使用lib: ["es2015", "dom"]
It seems that the problem is caused by targeting ES2016
. 看来该问题是由针对ES2016
引起的。
Are you targeting that for a reason? 您是否有针对性地定位? If you target es6
the error will probably go away. 如果您以es6
为目标,则错误可能会消失。
Another option is to specify the libraries for the compiler to use: 另一个选择是指定供编译器使用的库:
tsc -t ES2016 --lib "ES2016","DOM" ./your_file.ts
Which should also make the error go away. 这也应该使错误消失。
I'm not sure why the libs aren't used by default, in the docs for compiler options it states for the --lib
option: 我不确定为什么默认情况下不使用这些库,在文档的编译器选项中它声明了--lib
选项:
Note: If --lib is not specified a default library is injected. 注意:如果未指定--lib,则会注入默认库。 The default library injected is: 注入的默认库为:
► For --target ES5: DOM,ES5,ScriptHost ►对于--target ES5:DOM,ES5,ScriptHost
► For --target ES6: DOM,ES6,DOM.Iterable,ScriptHost ►对于--target ES6:DOM,ES6,DOM.Iterable,ScriptHost
But it doesn't state what are the default libraries when targeting ES2016
. 但是没有说明针对ES2016
的默认库是什么。
It might be a bug, try to open an issue, if you do please share the link here. 这可能是一个错误,请尝试打开一个问题,如果您这样做,请在此处共享链接。
use 采用
"lib": ["dom"]
in tsconfig.json 在tsconfig.json中
eg 例如
{
"compilerOptions": {
"lib": ["es5", "es6", "dom"],
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es6",
"moduleResolution": "node",
"jsx": "react"
},
"include": ["./src/**/*"]
}
What fixed it for me was changing tsconfig.json
's "target"
to "es6"
.为我修复的是将tsconfig.json
的"target"
更改为"es6"
。 It was "es2015"
before.之前是"es2015"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.