1 min read · Nov 21, 2023
--
In summary, `module.exports` is associated with CommonJS modules used in Node.js, while `export default` is associated with ES6 modules used in modern JavaScript environments, including browsers and newer versions of Node.js. If you are working in a mixed environment or using a transpiler like Babel, you might encounter code that uses both module systems.
- **CommonJS (Node.js):**
— `module.exports` is used in CommonJS, which is the module system used in Node.js.
— With `module.exports`, you can export an object, function, or any value as the module’s public API.
// Example using module.exports in Node.js
// File: myModule.js
const myFunction = () => {
// function logic
};
module.exports = myFunction;
// File: main.js
const myModule = require('./myModule');
myModule(); // Call the exported function
2. **ES6 Modules (Browsers, Frontend, and Modern Node.js):**
— `export default` is used in ECMAScript 6 (ES6) modules, which are the module system introduced in the ECMAScript 2015 specification and widely used in modern frontend development and in newer versions of Node.js.
— With `export default`, you can export a single value as the default export of a module.
// Example using export default in ES6 modules
// File: myModule.js
const myFunction = () => {
// function logic
};
export default myFunction;
// File: main.js
import myModule from './myModule';
myModule(); // Call the default exported function