Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

typescript - Why is --isolatedModules error fixed by any import?

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

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

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

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

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 --isolatedModules actually mean/do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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. isolatedModules forbids such files.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...