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?


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.


The correct way is to tell TypeScript what you want. If you don't want isolatedModules create tsconfig.json inside your test directory and add:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "isolatedModules": false
  },
}

Adding "isolatedModules": true to the config and then cheating TypeScript checker by adding empty export {} smells bad code to me.


Still having error despite you exporting things from that "error file"?

  1. Check if you don't export same name that you already export in another file (conflict)
  2. After your fix try to stop and start your npm/yarn runner (I experienced it cannot recover itself even after hard reload of the page especially when you have another error somewhere else)