简体   繁体   English

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

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

I have some code within which I'm using typeof window == "undefined" to check whether there is a browser environement.我有一些代码在其中使用typeof window == "undefined"来检查是否存在浏览器环境。 When I'm launching this code with ts-node , I'm getting this:当我使用ts-node启动这段代码时,我得到了这个:

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

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

AFAIK typeof is kind of operator that is safe to use with not defined variables, and it works well both in browser and in NodeJS environement. AFAIK typeof是一种可以安全使用未定义变量的运算符,它在浏览器和 NodeJS 环境中都能很好地工作。 But as far as I start to use it with ts-node , it starts to throw.但就我开始将它与ts-node一起使用时,它开始抛出。

My tsconfig.json我的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"
        ]
    }
}

So, what the trick?那么,有什么诀窍呢? Thanks in advance!提前致谢!

try add to lib in tsconfig "DOM"尝试在 tsconfig "DOM" 中添加到 lib

For me it worked to first declare the variable to TypeScript, so:对我来说,首先将变量声明为 TypeScript,所以:

declare var window;

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

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

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