Last updated: Feb 29, 2024
Reading time·2 min
The error "Cannot be compiled under '--isolatedModules' because it is
considered a global script file" occurs when we have a file in our project that
doesn't contain an import
or export
statement.
To solve the error, add an export {}
line to the file to make it an ES
module.
Here is an example of how the error occurs.
// ⛔️ Error: All files must be modules when // the '--isolatedModules' flag is provided. // 'index.ts' cannot be compiled under // '--isolatedModules' because it is considered // a global script file. Add an import, export, // or an empty 'export {}' statement to make it a module.ts(1208) const country = 'Austria';
The index.ts
file doesn't contain any import
or export
statements, so it
is not considered an
ES Module
by TypeScript.
To solve the error, add an import or export statement to the module.
const country = 'Austria'; export {}; // 👈️ if you don't have anything else to export
We used the export {}
line in our index.ts
file to mark it as a module. A
module is a file that contains at least 1 import
or export
statement.
import
or export
statement, it gets treated like a global script file and the isolatedModules
setting in your tsconfig.json
file forbids this behavior..ts
file in your projectMake sure that you don't have an empty .ts
file somewhere in your project,
and if you do, either remove the file or add an export {}
line to make it an
ES module.
Empty files are treated like legacy scripts, which is not allowed with
isolatedModules
enabled.
isolatedModules
to false
in tsconfig.json
If this doesn't get the error resolved, try setting isolatedModules
to false
in your tsconfig.json file.
{ "compilerOptions": { "isolatedModules": false, // ... rest } }
When the
isolatedModules
option is set to true
, all files in your project must be modules (must contain
at least 1 import
or export
statement).
I've also written a detailed guide on how to import values from another file in TS.
Another thing that may cause an error with isolatedModules
set to true
is if
you are importing a type and then re-exporting it.
import { EmployeeType } from './another-file'; // ⛔️ Error: Re-exporting a type when the '--isolatedModules' flag is provided requires using 'export type'.ts(1205) export { EmployeeType };
Because of how transpilers work, the setting wants us to explicitly use the
export type
syntax.
import { EmployeeType } from './another-file'; export type { EmployeeType };
The export type
syntax guarantees that the export statement will be removed
from your code during compilation and it won't end up causing a runtime error
because you are trying to export something that doesn't exist (types get removed
during compilation).