繁体   English   中英

typeof window == “undefined” 在使用 ts-node 时抛出错误

[英]typeof window == “undefined” throws an error while using ts-node

我有一些代码在其中使用typeof window == "undefined"来检查是否存在浏览器环境。 当我使用ts-node启动这段代码时,我得到了这个:

typings/Console.ts:36:10 - error TS2304: Cannot find name 'window'.

36      typeof window == "undefined"
               ~~~~~~

AFAIK typeof是一种可以安全使用未定义变量的运算符,它在浏览器和 NodeJS 环境中都能很好地工作。 但就我开始将它与ts-node一起使用时,它开始抛出。

我的tsconfig.json

{
    "compilerOptions": {
        "module": "CommonJS",
        "target": "es5",
        "moduleResolution": "node",
        "baseUrl": "src",
        "allowSyntheticDefaultImports": true,
        "noImplicitAny": true,
        "strict": false,
        "sourceMap": true,
        "traceResolution": true,
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "strictNullChecks": true,

        "allowJs": false,
        "declaration": false,
        "removeComments": true,
        "noLib": false,
        "preserveConstEnums": true,
        "suppressImplicitAnyIndexErrors": true,
        "types": [ "node" ],
        "lib": [ "es6" ],
        "downlevelIteration": true,
        "resolveJsonModule": true,
        "typeRoots": [
            "../node_modules/@types"
        ]
    }
}

那么,有什么诀窍呢? 提前致谢!

尝试在 tsconfig "DOM" 中添加到 lib

对我来说,首先将变量声明为 TypeScript,所以:

declare var window;

if(typeof window == "undefined"){
// code
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM