簡體   English   中英

node-ts 顯示“錯誤 TS2304:找不到名稱 '__DEV__'”

[英]node-ts shows “error TS2304: Cannot find name '__DEV__'”

我最近將__DEV__添加到我的__DEV__中的某個 TypeScript 文件中。 在 VSCode 中,這不會被標記為錯誤。

但是,當我運行該項目時,我立即收到錯誤

error TS2304: Cannot find name '__DEV__'.

我嘗試將/* global __DEV__ */到文件頂部。 錯誤仍然存​​在。

我嘗試在我declare var __DEV__: boolean;地方添加一個global.d.ts文件declare var __DEV__: boolean; . 錯誤仍然存​​在。

這是我的 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"
 ]
}

編輯:該項目是通過launch.json中的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"
            ]
        }
    ]
}

有一個關於打字的警告,在 repohttps://github.com/TypeStrong/ts-node#help-my-types-are-missing上正式表達。

綜上所述,您可以通過以下操作來解決問題:

像這樣為typings目錄創建結構:

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

index.d.ts是你的內容:

declare var __DEV__: boolean

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

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

最后,唯一真正有效的是將__DEV__變量移動到eval

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

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

index.d.ts中的聲明僅解決設計時錯誤。 運行時錯誤不受它的影響。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM