Fix: SyntaxError: The requested module does not provide an export named default


SampleModule.mjs
module.exports = () => {
    console.log('Learning NodeJs.');
};
index.mjs
import sampleModule from './sampleModule.mjs';
sampleModule();
Execution Error:
% node --experimental-modules index.mjs

file:///Users/c2ctechtv/Desktop/node-examples/index.mjs:1
import sampleModule from './sampleModule.mjs';
       ^^^^^^^^^^^^
SyntaxError: The requested module './sampleModule.mjs' does not provide an export named 'default'
    at ModuleJob._instantiate (node:internal/modules/esm/module_job:122:21)
    at async ModuleJob.run (node:internal/modules/esm/module_job:188:5)
    at async DefaultModuleLoader.import (node:internal/modules/esm/loader:228:24)
    at async loadESM (node:internal/process/esm_loader:40:7)
    at async handleMainPromise (node:internal/modules/run_main:66:12)
SyntaxError- The requested module does not provide an export named default

Fix:

This error occurs when you try to import a default export from an ES module, but the module does not contain a default export named 'default'.

We make the following changes to our files to fix this error,

SampleModule.mjs
export const message = 'Learning NodeJs.';
index.mjs
import { message } from './sampleModule.mjs';
console.log(message);
Execution:
% node --experimental-modules index.mjs
Learning NodeJs.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap