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 中添加到 lib "DOM"
对我来说,首先向 TypeScript 声明变量是可行的,所以:
declare var window;
if(typeof window == "undefined"){
// code
}
我有一些代码,我在其中使用 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 中添加到 lib "DOM"
对我来说,首先向 TypeScript 声明变量是可行的,所以:
declare var window;
if(typeof window == "undefined"){
// code
}