w3resource

Practical Guide to Mixing ES6 and CommonJS Modules


Mixing ES6 and CommonJS Modules:

Write a JavaScript program that uses an ES6 module to import a CommonJS module and vice versa.

This exercise demonstrates how to use ES6 modules with CommonJS modules and vice versa. Due to their different module systems, special handling is required to make them work together.

Solution: Using ES6 to Import a CommonJS Module

Code:

File: commonJSModule.js

This file defines a CommonJS module.

// commonJSModule.js
 // Exporting a function using CommonJS
module.exports = {
  greet: function (name) {
    return `Hello, ${name}!`;
  },
};

File: es6Module.js

This file imports the CommonJS module using ES6 syntax.

// es6Module.js
// Importing the CommonJS module in an ES6 module
import commonJSModule from './commonJSModule.js';

// Using the imported module
console.log(commonJSModule.greet('Sara')); // Logs "Hello, Alice!"

Output:

Hello, Sara!

Explanation:

  • The commonJSModule.js file exports an object using module.exports.
  • The ES6 module (es6Module.js) imports the CommonJS module using the import keyword.
  • Modern bundlers (like Webpack or Node.js with ES6 support) handle this conversion seamlessly.

Improve this sample solution and post your code through Disqus

Previous: Learn to Dynamically Override JavaScript Module Exports.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.