How do I fix "unexpected token 'export'" error when I try to use uuid package?

Viewed 3673

I'm working in a vue.js application with node.js in the backend. We've installed the npm package uuid in the backend but it's not working.

Our package.json file in the backend contains this:

"uuid": "^8.2.0",

In our controller, in the constructor, we have this:

this.uuid = require("uuid");

And we use it like this:

const id = this.uuid.v1();

The problem is, when we call the endpoint on the backend, we get this error:

C:\...\backend\node_modules\uuid\dist\esm-browser\index.js:1
export { default as v1 } from './v1.js';
^^^^^^
SyntaxError: Unexpected token 'export'

Googling this issue, the only solutions I've found involve importing v1 specifically, such as this:

import {v1 as uuid} from "uuid";

But since we're using node.js on the backend, we get this error:

SyntaxError: Cannot use import statement outside a module

How can I solve this problem?

2 Answers

I have been there. Used this approach:

const uuid = require('uuid');
const newUuid = uuid.v4();

You may use .v1() instead of .v4().

You should first export your functions (that you need in other modules) in v1.js like below-

function xyz() {
}

module.exports = xyz;

You can then use this in the respective files as-

const xyz = require(‘../pathname’);
Related