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

Lim*_*mbo 3 javascript typeof node.js typescript ts-node

我有一些代码用来typeof window == "undefined"检查是否存在浏览器环境。当我使用 启动此代码时ts-node,我得到以下信息:

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

36      typeof window == "undefined"
               ~~~~~~
Run Code Online (Sandbox Code Playgroud)

AFAIKtypeof是一种可以安全地与未定义的变量一起使用的运算符,并且它在浏览器和 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"
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

那么,有什么技巧呢?提前致谢!

小智 5

尝试添加到 tsconfig “DOM” 中的 lib