Typescript cannot find name window or document

前端 未结 2 1033
感动是毒
感动是毒 2020-12-01 17:48

For either case:

document.getElementById(\'body\');
// or
window.document.getElementById(\'body\');

I get error TS2304: Cannot find n

相关标签:
2条回答
  • 2020-12-01 18:10

    It seems that the problem is caused by targeting ES2016.
    Are you targeting that for a reason? If you target es6 the error will probably go away.

    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:

    Note: If --lib is not specified a default library is injected. The default library injected is:
    ► For --target ES5: DOM,ES5,ScriptHost
    ► For --target ES6: DOM,ES6,DOM.Iterable,ScriptHost

    But it doesn't state what are the default libraries when targeting ES2016.
    It might be a bug, try to open an issue, if you do please share the link here.

    0 讨论(0)
  • 2020-12-01 18:13

    use

    "lib": ["dom"]
    

    in tsconfig.json

    e.g.

    {
      "compilerOptions": {
        "lib": ["es5", "es6", "dom"],
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es6",
        "moduleResolution": "node",
        "jsx": "react"
      },
      "include": ["./src/**/*"]
    }
    
    0 讨论(0)
提交回复
热议问题