【问题标题】:node-ts shows "error TS2304: Cannot find name '__DEV__'"node-ts 显示“错误 TS2304:找不到名称 '__DEV__'”
【发布时间】:2020-12-08 18:22:15
【问题描述】:

我最近在我的 NodeJS 项目中的某个 TypeScript 文件中添加了 __DEV__。在 VSCode 中,这不会被标记为错误。

但是,当我运行项目时,我立即得到错误

error TS2304: Cannot find name '__DEV__'.

我尝试将/* global __DEV__ */ 添加到文件顶部。错误仍然存​​在。

我尝试在declare var __DEV__: boolean; 的位置添加一个global.d.ts 文件。错误仍然存​​在。

这是我的 tsconfig:

{
 "compilerOptions": {
  "target": "es6",
  "lib": [
   "es2017","es2015","dom","es6"
  ],
  "module": "commonjs",
  "outDir": "./",
  "sourceMap": true,
  "esModuleInterop": true,
  "strict": false,
  "resolveJsonModule": true,
  "downlevelIteration": true
 },
 "include": [
  "**.ts"
 ],
 "exclude": [
  "node_modules"
 ]
}

编辑: 该项目通过 VSCode 中的 launch.json 文件启动。以下是它的内容:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Current TS File",
            "type": "node",
            "request": "launch",
            "args": ["${relativeFile}"],
            "runtimeArgs": ["--nolazy", "-r", "ts-node/register", "--max-old-space-size=32768"],
            "cwd": "${workspaceRoot}",
            "protocol": "inspector",
            "internalConsoleOptions": "openOnSessionStart",
            "console": "integratedTerminal",
            "stopOnEntry": false,
            "skipFiles": [
                "${workspaceFolder}/node_modules/**/*.js",
                "<node_internals/**/*.js"
            ]
        }
    ]
}

【问题讨论】:

  • 您遗漏了最重要的信息。 如何您正在运行该项目?你向ts-node 传递什么参数?此外,您的 tsconfig.json 存在语法错误,因为它不是有效的 JSON,这将导致某些工具失败。
  • @AluanHaddad 查看编辑。 tsconfig.json 现在应该是有效的 json。

标签: node.js typescript ts-node


【解决方案1】:

在 repo https://github.com/TypeStrong/ts-node#help-my-types-are-missing 上正式表达了关于打字的警告。

总而言之,您可以通过以下方式解决问题:

像这样为typings dir 创建结构:

- tsconfig.json
- typings
-- global
--- index.d.ts

index.d.ts 是你的内容:

declare var __DEV__: boolean

然后将typeRoots 添加到您的tsconfig.json

{
  "compilerOptions": {
    "typeRoots" : ["./node_modules/@types", "./typings"]
  }
}

【讨论】:

  • 这似乎有效。但是,它并没有回答为什么 __DEV__ 根本就不见了。 __DEV__ 不应该是所有 NodeJS 环境中的定义变量吗?
  • 我不认为 var 是默认定义的。我会说你可以改用process.env.NODE_ENV
【解决方案2】:

最后,唯一真正有效的是将__DEV__ 变量移动到eval

const isInDebugMode = () => {
  return eval('__DEV__');
}

不理想,但它完成了工作。

index.d.ts 中的声明仅解决了设计时错误。运行时错误不受它的影响。

【讨论】:

    猜你喜欢
    • 2016-12-18
    • 2019-05-06
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多