Cannot be compiled under ‘isolatedModules’ because it is considered a global script file

It is a very common error in TypeScript that beginners often face. When this error occurs, your code editor might display the following error message 👇

Cannot be compiled under 'isolatedModules' because it is considered a global script file error pic no. 1

Why this error occurs ?

The error “Cannot be compiled under ‘–isolatedModules’ because it is considered a global script file” occurs when a file in our project doesn’t have an import or export statements.

For example, let’s say we have a file named index.ts in our project. Inside this file, we have a variable called “message” that stores a string value.

Here you will get an error that “Cannot be compiled under ‘–isolatedModules’ because it is considered a global script file”.

index.ts :

// ⛔️ 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 message = "Hello, world!";
console.log(message);

How to fix this error ?

There are several ways to fix the error :

1. Add an import or export statement to the module:

To resolve the error and mark the index.js file as a module, we can add the “export” keyword at the beginning of the file. A module is a file that includes at least one `import` or `export` statement.

export const message = "Hello, world!";
//console.log(message);

By adding the `export` keyword, we indicate that the file is a module and can be used for importing or exporting variables, functions, or other entities.

2. Set the `isolatedModules` to false :

If the first method doesn’t fix your problem you can try another approach. Open the `tsconfig.json` file in your project and go to `isolatedModules` property. By default, this property is set to true. Change the value of `isolatedModules` to false.

Cannot be compiled under 'isolatedModules' because it is considered a global script file error pic no. 2

This change will disable the strict enforcement of isolated modules, which might help in fixing the problem you are facing.

3. Make sure you don’t have an empty `.ts` file in your project :

Make sure you don’t have any empty .ts files in your project. If you do, you have two options: either delete the empty file or add the line “export {}” to the file to make it a module.

This is necessary because empty files are considered legacy scripts, and when you have the `isolatedModules` flag enabled, empty files are not allowed.

I hope this article helped you to solve the error you were facing. 🙏

Leave a Comment