#
Module has no default export Error in TypeScript
The "Module has no default export" error occurs when we try to import as
default from a module that doesn't have a default export.
To solve the error make sure the module has a named export and wrap the import
in curly braces, e.g.
import {myFunction} from './myModule'
.
Here is an example of how the error occurs. This is our
index.ts
file.
export function sum(a: number, b: number) {
return a + b;
And this is a file that imports the function from
index.ts
.
import sum from './index';
console.log(sum(5, 15));
Notice that in our
index.ts
file, we used a
named
export, but when we
imported the function in the other file we used a
default
import. This is the
reason the error occurs.
To solve the error, make sure:
-
To wrap named exports in curly braces when importing them
-
Use the
default
keyword when exporting a value as a default export
-
Each module only has a maximum of 1 default export
but could have multiple named exports
#
Solve the error using a
default
export
Here is an example of how to solve the error using a default export.
export default function sum(a: number, b: number) {
return a + b;
And import the function in the other file.
import sum from './index';
console.log(sum(5, 15));
Notice that we do not use curly braces when working with default imports.
You can have a maximum of 1
default
export per file.
If you are exporting a variable 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.
const str = 'hello';
export default str;
You can only have a single
default
export per module, but you can have
multiple
named
exports.
#
Solve the error using a
named
export
Here is how you use named imports/exports.
export function sum(a: number, b: number) {
return a + b;
And now we use a named import in the other file.
import { sum } from './index';
console.log(sum(5, 15));
Notice the curly braces, this is how we import a named export.
You have to be consistent with your imports and exports. Don't use curly braces when importing default exports and use curly braces when importing named exports.
#
Using both named and default exports
You can also mix and match, here's an example.
export const num = 33;
export default function sum(a: number, b: number) {
return a + b;
And here are the imports.