You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决TypeScript中‘Cannot redeclare block-scoped variable’错误?

解决TypeScript中“Cannot redeclare block-scoped variable”错误

编辑说明:
在报错文件的首行添加export {};,已解决所有问题。

问题描述

当在其他文件/文件夹中通过require导入代码时,反复遇到如下错误:

示例场景

我有一个导出isArray()函数的文件,内容如下:

const isArray = () => {...};

module.exports = isArray;

在另一个文件中通过const isArray = require('./isArray.ts');导入后,require语句和函数定义处均出现错误提示:Cannot redeclare block-scoped variable 'isArray'。

导入dotenv、express等第三方包时也会触发该错误。请问如何避免这个错误?

补充信息

package.json

{
  ...
  "main": "./src/api/server.ts",
  "scripts": {
    "dev": "npx nodemon ./src/api/server.ts",
    ...
  },
  ...
  "dependencies": {
    "axios": "^0.27.2",
    "body-parser": "^1.20.0",
    "cors": "^2.8.5",
    "express": "^4.18.1",
    "firebase": "^9.7.0",
    "firebase-admin": "^10.2.0",
    "moment": "^2.29.3",
    "morgan": "^1.10.0",
    "plaid": "^10.3.0",
    "uniqid": "^5.4.0",
    "ts-node": "^10.7.0",
    "typescript": "^4.6.4"
  },
  "devDependencies": {
    "dotenv": "^16.0.0",
    "nodemon": "^2.0.16"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "lib": ["es6"],
    "esModuleInterop": true,
    "target": "es6",
    "noImplicitAny": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "rootDir": "./src",
    "outDir": "./dist",
    "baseUrl": ".",
    "paths": {
        "*": [
            "node_modules",
            "src-broken/types"
        ]
    }
},
"include": [
    "./src"
]
}

内容的提问来源于stack exchange,提问作者Brace Sproul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 20:45:55