Borislav Hadzhiev
Wed Feb 23 2022·2 min read
Photo by Ömürden Cengiz
The "does not contain a default export" error occurs when we try to use a
default import to import 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.
// 👇️ named export export function sum(a, b) { return a + b; }
And we try to use a default import for a named export.
// ⛔️ Error: Attempted import error: // file does not contain a default export // 👇️ using a default import import sum from './another-file'; console.log(sum(5, 10));
Notice that in another-file.js
we used a named export to export the sum
function and in index.js
we used a default import. This is the reason the
error occurs.
To solve the "does not contain a default export" error, make sure:
default
keyword when exporting a value as a default exportHere is an example of how to solve the error using a named import.
// 👇️ named export export function sum(a, b) { return a + b; }
And import the function in the index.js
file.
// 👇️ named import import {sum} from './another-file'; console.log(sum(5, 10));
Notice that we don't use the default
keyword for named exports and wrap a
named import in curly braces.
Here is an example of how to solve the error using default export and import.
// 👇️ default export export default function sum(a, b) { return a + b; }
And now we use a default import in the index.js
file.
// 👇️ default import import sum from './another-file'; console.log(sum(5, 10));
Notice that we do not use curly braces when working with default imports.
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.
// 👇️ default export const example = 'hello'; export default example;
You can also mix and match, here's an example.
// 👇️ default export export default function sum(a, b) { return a + b; } // 👇️ named export export const num = 20;
And here are the imports.
// 👇️ default and named imports import sum, {num} from './another-file'; console.log(sum(num, 10));
We used a default import to import the sum
function and a named import to
import the num
variable.
To solve the "does not contain a default export" error, be consistent with your ES6 imports and exports. If a value is exported as a default export, it has to be imported as a default import and if it's exported as a named export, it has to be imported as a named import.