javascript - typeof window == "undefined"在使用 ts-node 时抛出错误

标签 javascript node.js typescript typeof ts-node

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

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

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

AFAIK typeof 是一种可以安全使用 undefined variable 的运算符,它在浏览器和 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

关于javascript - typeof window == "undefined"在使用 ts-node 时抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61871197/

相关文章:

javascript - meteor 错误: ENOTEMPTY: directory not empty

node.js - 是否可以离线安装全局 Node 包?

angular - 如何避免 RxJs 订阅回调 hell ?

javascript - Zone.js 检测到 ZoneAwarePromise `(window|global).Promise` 已被覆盖

node.js - 如何从 Firebase Cloud Function 访问 firestore.Timestamp

javascript - 无法进入 contentEditable 中的空段落

javascript - 在xpath中表达文本框的值?

javascript - 从 WebSQL Javascript 命令返回一个变量

javascript - 收集 Api 返回的数组

node.js - 使用 Puppeteer 如何单击选择器的父元素?