Clifton Labrum
Clifton Labrum

Reputation: 14060

How Can I Use Named Module Exports in Node 16 App?

I'm using Node 16.3.0 and Express 4.17.1 (though my Node version is flexible)

I have a session.js file that's like this:

// session.js

exports.fetchUserId = async function(token){
  ...
}

exports.save = async function(userId){
  ...
}

Then over in my app.js file, I try to do this:

// app.js

import session from './session.js'

I get the following error:

import session from './session.js'
       ^^^^^^^
SyntaxError: The requested module './session.js' does not provide an export named 'default'

...and then I want to use session in app.js like this:

let userId = await session.fetchUserId(req.body.token)

I have tried the following without any luck:

  1. Adding "type": "module" to package.json
  2. This answer by doing npm i esm
  3. Using nodemon --experimental-modules app.js

My code works fine when used in a NuxtJS project, but I'm trying a vanilla Node/Express app and the named exports don't work.

Any idea what I'm doing wrong?

Upvotes: 1

Views: 2395

Answers (1)

Yousaf
Yousaf

Reputation: 29282

Problem in your code is that you are mixing the ES modules with CommonJS modules.

By default, node treats each javascript file as a CommonJS module but with the following in the package.json file

"type": "module"

you are telling node to treat each javascript file as a Ecmascript module but in session.js file, you are using the CommonJS module syntax to export the functions.

Solutions

You could solve your problem using one of the following options:

  • Change the extension of the session.js file to .cjs. (Don't forget to change the extension in the import statement in app.js file as well).

    Changing the extension to .cjs will tell node to treat session.cjs file as a CommonJS module.

  • Just use ES modules and change the exports in session.js file as shown below:

    export const fetchUserId = async function(token){ ... }
    
    export const save = async function(userId) { ... }
    

    and change the import statement in app.js file as:

    import * as session from "./session.js";
    

Upvotes: 1

Related Questions