Attempted Import Error: ‘Uuid’ Does Not Contain A Default Export – How To Fix It?

Attempted import error: 'uuid' does not contain a default export

Don’t worry about getting the error “Attempted import error: ‘uuid’ does not contain a default export”. This article will share what causes this error and how to fix it. Let’s read it now.

When does the error “Attempted import error: ‘uuid’ does not contain a default export” appear?

Uuid stands for Universally Unique IDentifier, which can be understood as a unique identifier, and there is no second one.

In Node.js, you can install uuid with the following command:

npm install uuid

Uuid@7 does not come with native ECMAScript Modules (ESM) support for Node.js. Therefore, only named exports are supported when used with Node.js ESM. The error will occur if you import a function of uuid without using import with named export.

Example:

import uuid from 'uuid';

Output:

Attempted import error: 'uuid' does not contain a default export (imported as 'uuid').

How to solve this error?

To solve this, you need to use named exports in your import statement.

Using the import syntax

The following example describes importing a v4 export using the import syntax.

Example:

import { v4 as uuidv4 } from 'uuid';
console.log(uuidv4());

Output:

b4197b4d-80df-472a-889e-a20ea96beb38

Uuid.v4 has a function to create UUID RFC version 4 (random).

If you want to use predefined random values, let’s see the following example:

import { v4 as uuidv4 } from 'uuid';

// Use random option with predefined random values
const v4ot = {
  random: [0x34, 0x43, 0x7c, 0x41, 0x3f, 0xea, 0x43, 0xd0, 0x90, 0x86, 0xe1, 0xa2, 0x3a, 0xa5, 0xbd, 0x18],
};

console.log(uuidv4(v4ot));

Output:

34437c41-3fea-43d0-9086-e1a23aa5bd18

Using the require() method

If you are using the old version, you can use the require() method.

The require function reads a JavaScript file, then executes the file, and finally returns the export object.

The syntax for require uuid is as follows:

const { v4: uuidv4 } = require('uuid');

Here is a specific example:

const { v4: uuidv4 } = require('uuid');
console.log(uuidv4());

Output:

be57a926-ada3-4c4f-bc25-039e949adf26

Summary

This article has shown how to solve the error “Attempted import error: ‘uuid’ does not contain a default export”. I hope the information in this article will be helpful to you. If you have any problems, please comment below. I will answer as possible. Thank you for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *