typescript 为什么任何导入都修复了 --isolatedModules 错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/56577201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 08:03:47  来源:igfitidea点击:

Why is --isolatedModules error fixed by any import?

typescript

提问by Svish

In a create-react-app typescript project, I tried to write this just to test some stuff quickly:

在 create-react-app 打字稿项目中,我试图写这个只是为了快速测试一些东西:

// experiment.test.ts
it('experiment', () => {
  console.log('test');
});

But it gives me the following error, with a red squiggly beneath it:

但它给了我以下错误,下面有一个红色的波浪线it

All files must be modules when the '--isolatedModules' flag is provided.

提供“--isolatedModules”标志时,所有文件都必须是模块。

However, if I change the file to the following, then everything apparently is fine (except for the unused import of course):

但是,如果我将文件更改为以下内容,那么一切显然都很好(当然,未使用的导入除外):

// experiment.test.ts
import { Component} from 'react'; // literally anything, don't even have to use it

it('test', () => {
  console.log('test');
});

Why? What is happening here? What does --isolatedModulesactually mean/do?

为什么?这里发生了什么?--isolatedModules实际上是什么意思/做什么?

回答by Titian Cernicova-Dragomir

Typescript treats files without import/exports as legacy script files. As such files are not modules and any definitions they have get merged in the global namespace. isolatedModulesforbids such files.

Typescript 将没有导入/导出的文件视为遗留脚本文件。由于这些文件不是模块,它们的任何定义都已合并到全局命名空间中。isolatedModules禁止此类文件。

Adding any import or export to a file makes it a module and the error disappears.

向文件添加任何导入或导出使其成为模块并且错误消失。

Also export {}is a handy way to make a file a module without importing anything.

也是export {}一种在不导入任何内容的情况下使文件成为模块的便捷方法。