Last updated: Feb 28, 2024
Reading timeยท3 min
The error "File is not a module" occurs when we forget to use the export
keyword to export a value from a file or the IDE glitches.
To solve the error, make sure to export the values you're trying to import in other files and if necessary rewrite the import path and restart your IDE.
Here is an example of how the error occurs. This is a file called
another-file.ts
.
// ๐๏ธ forgot to export function sum(a: number, b: number) { return a + b; }
And here is a file called index.ts
that tries to import from
another-file.ts
.
// โ๏ธ File is not a module.ts(2306) import { sum } from './another-file'; console.log(sum(50, 50));
The file another-file.ts
is not a
module,
because it doesn't have an export
or import
statement.
To solve the error, we have to export all of the members we intend to import in other files.
// ๐๏ธ named export export function sum(a: number, b: number) { return a + b; }
We used the export
keyword to export the sum
function. Now we can import it
in the index.ts
file.
// ๐๏ธ named import import { sum } from './another-file'; console.log(sum(50, 50)); // ๐๏ธ 100
The error "File is not a module" simply means that the file does not contain any
export
or import
statements.
Any file that contains at least 1 import
or export
statement is considered a
module.
I've written a detailed guide on how to import values from another file in TS.
Another common cause of the error is if our IDE (e.g. VSCode or Sublime) glitches.
If you have exported the values you're trying to import, it's best to remove the
path in the import
statement and try to use your IDE to autocomplete the path,
so it can pick it up.
Make sure to save your file and restart your IDE/server if necessary.
The examples above used named
exports and imports. You could also use a
default
export and import.
// ๐๏ธ default export export default function sum(a: number, b: number) { return a + b; } // ๐๏ธ named export export const num = 250;
And you would import the default export without wrapping it in curly braces.
// ๐๏ธ default and named imports import sum, { num } from './another-file'; console.log(sum(num, num)); // ๐๏ธ 500
Important: If you are exporting a variable (or an arrow function) as a default export, you have to declare it on 1 line and export it on the next. You can't declare and default export a variable on the same line.
The main difference between named and default exports and imports is that you can have multiple named exports per file, but you can only have a single default export.
In my experience, most real-world codebases exclusively use named exports and imports, because they make it easier to leverage your IDE for auto-completion and auto-imports.
You also don't have to think about which members are exported using a default
or named
export.
You can learn more about the related topics by checking out the following tutorials: