不相关文件中的“无法重新声明块范围变量" [英] 'Cannot redeclare block-scoped variable' in unrelated files

查看:28
本文介绍了不相关文件中的“无法重新声明块范围变量"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个简单的 TS 包,用作 CommonJS 模块并且没有导出.TS文件编译成同名的JS文件,作为require('package/option-foo')使用.

There is a simple TS package that is used as CommonJS modules and has no exports. TS files are compiled to JS files with the same name and used as require('package/option-foo').

tsconfig.json:

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5"
  }
}

option-foo.ts:

option-foo.ts:

declare const GlobalVar: any;

function baz() {}

if (GlobalVar.foo) GlobalVar.baz = baz;

option-bar.ts:

option-bar.ts:

declare const GlobalVar: any;

function baz() {}

if (GlobalVar.bar) GlobalVar.baz = baz;

这里的重要部分是option-foooption-bar从未一起使用.项目中还有其他免费的 TS 文件,但它们不影响任何东西,只需要在一次 tsc 运行中转译为 JS.

The important part here is that option-foo and option-bar are never used together. There are other complimentary TS files in the project, but they don't affect anything, just needed to be transpiled to JS in one tsc run.

tsc 运行时,它抛出

无法重新声明块范围变量GlobalVar".

Cannot redeclare block-scoped variable 'GlobalVar'.

重复的函数实现.

无法重新声明块范围变量GlobalVar".

Cannot redeclare block-scoped variable 'GlobalVar'.

重复的函数实现.

用于两个文件中的 GlobalVarbaz.

for GlobalVar and baz in both files.

如何在不复杂化构建过程或这两个 TS 文件的输出的情况下处理这种情况?

How can this be treated without complicating build process or the output from these two TS files?

推荐答案

TL;DR 只需在文件的最外层范围内写入 export {}.

TL;DR Just write export {} in the outermost scope of your files.

在某些时候,需要对文件应该被视为模块(并有自己的范围)还是脚本(并共​​享其他脚本的全局范围).

At some point there needs to be a semantic disambiguation for whether a file should be treated as a module (and have its own scope) or a script (and share the global scope with other scripts).

在浏览器中,这很容易 - 您应该能够使用 <script type="module"> 标记,并且您将能够使用模块.

In the browser, this is easy - you should be able to use a <script type="module"> tag and you'll be able to use modules.

但是其他使用 JavaScript 的地方呢?不幸的是,目前还没有标准的方法来区分.

But what about any other place that utilizes JavaScript? Unfortunately there isn't a standard way at this point to make that distinction.

TypeScript 决定解决这个问题的方法是简单地声明一个模块是任何包含导入或导出的文件.

The way that TypeScript decided to tackle the problem was to simply state that a module is any file which contains an import or export.

因此,如果您的文件没有任何类型的顶级 importexport 语句,那么您偶尔会看到全局声明相互干扰的问题.

So if your file doesn't have any sort of top-level import or export statements, then you'll occasionally see issues with global declarations interfering with each other.

要解决这个问题,您可以简单地使用一个 export 语句,该语句不导出任何内容.换句话说,只要写

To get around this, you can simple have an export statement that exports nothing. In other words, just write

export {};

位于文件顶层的某处.

这篇关于不相关文件中的“无法重新声明块范围变量"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆