问题:

每当我在一个以上的类型脚本文件中导入相同的NPM模块时,只要我运行类型脚本编译器tsc,我就得到错误"error TS2451: Cannot redeclare block-scoped variable 'os'".我的项目设置如下所示.

我正在使用NodeJS v18.15.0.


设置:

目录 struct

Project_Root
├─ 双手
├─ Worker.ts
├─ Package.json
└─ Tsconfig.json

双手

const worker = require('./worker');
const os = require('os');

console.log('name = ' + worker.getName() );
console.log('memory = ' + os.freemem() );

Worker.ts

const os = require('os');

module.exports =
    class worker {
        static getName() : string { return "worker-" + os.freemem(); }
    }

Package.json

{
  "devDependencies": {
    "@types/node": "^18.15.11",
    "typescript": "^5.0.3"
  }
}

Tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": false
  },
  "exclude": ["node_modules"]
}

项目要求:

  • Requirement #1:没有外部包(RequireJS/Babel/webpack/等),磁盘空间有限.
  • Requirement #2:IDE Inteli-Sense应该有效.我们可以使用任何IDE.
  • Requirement #3:我们需要使用CommonJS风格的"Required"关键字进行导入.

我try 了以下几点:

我在以下帖子中try 了前三名的答案,但没有成功:

Related Posts Outcome
Error TS2451: Cannot redeclare block-scoped variable '$' Same error (after adding the "skipLibCheck: true" flag)
How to solve this Cannot redeclare block scoped variable 'ngDevMode'? Not Applicable (I am not using Angular)
TS2451: Cannot Redeclare Block-scoped Variable Not Applicable (I am not using ESLint)
Getting build error in angular CLI: Cannot redeclare block-scoped variable 'ngDevMode' Not Applicable (I am not using Angular)
Import npm JS Module in TypeScript Not Applicable (I am not using Electron)

推荐答案

这是因为TypeScrip没有考虑这两个文件模块,并使它们共享它们的作用域.您可以使用tsconfig中的moduleDetection字段强制将它们识别为模块:

{
  "compilerOptions": {
    "moduleDetection": "force"
  }
}

There's a discussion about this on the TS GitHub Repo

Javascript相关问答推荐

JavaScript:循环访问不断变化的数组中的元素

使用CDO时如何将Vue组件存储在html之外?

容器如何更改默认插槽中子项的显示?

如何获取转换字节的所有8位?

仅圆角的甜甜圈图表

如何访问Json返回的ASP.NET Core 6中的导航图像属性

基于变量切换隐藏文本

类型自定义lazy Promise. all

InDesign—创建一个独立的窗口,在文档中进行更正时保持打开状态

为什么我的列表直到下一次提交才更新值/onChange

如何从一个列表中创建一个2列的表?

v—自动完成不显示 Select 列表中的所有项目

使用原型判断对象是否为类的实例

material UI按钮组样式props 不反射

提交链接到AJAX数据结果的表单

如何将数组用作复合函数参数?

如何利用CSS中的隐藏元素实现平滑扩展和防止网格行间隙

更改agGRID/Reaction中的单元格格式

在Java脚本中构建接口的对象

Promise.race()返回已解析的promise ,而不是第一个被拒绝的promise