export default {} (ES6 模块 – ESM)

  • 适用于 ES6+ 版本的 JavaScript 模块 (import/export)。
  • 主要用于前端框架(如 React、Vue)和现代 Node.js 环境(需要 type: “module” 或 .mjs 扩展名)。
  • 只能有 一个 export default,但可以搭配多个 export 进行命名导出。

使用 import 语法导入

// module1.js
export default {
name: “ES Module”,
sayHello() {
console.log(“Hello from ESM”);
},
};

// main.js
import myModule from “./module1.js”;
console.log(myModule.name); // “ES Module”
myModule.sayHello(); // “Hello from ESM”

module.exports = {} (CommonJS – CJS)

  • 适用于 Node.js(默认模块系统)。
  • 不能和 import/export 直接混用(除非使用 import.meta.require)。
  • module.exports 可以是 任何值(对象、函数、类等)。

使用 require 语法导入

// module2.js
module.exports = {
name: “CommonJS Module”,
sayHello() {
console.log(“Hello from CommonJS”);
},
};

// main.js
const myModule = require(“./module2.js”);
console.log(myModule.name); // “CommonJS Module”
myModule.sayHello(); // “Hello from CommonJS”

区别对比

特性 export default {} module.exports = {}
模块系统 ES6 (ESM) CommonJS (CJS)
适用环境 现代浏览器、Node.js (ESM 模式) Node.js (默认)
语法 import / export require / module.exports
兼容性 需要 ES6+ 适用于所有 Node.js 版本
可导出内容 任何值,但只能有一个 default 任何值
是否支持命名导出 export { a, b } ❌(只能 exports.a = ...
动态导入 import() require()

在 Node.js 中使用 import/export

方法1、需要在 package.json 中添加

{
“type”: “module”
}

方法2、使用 .mjs 文件扩展名

import myModule from “./module.mjs”;

在 CommonJS 中使用 export default 语法

由于 export default 是 ES6 语法,而 CommonJS 默认使用 module.exports,可以这样模拟:

// module3.js
module.exports = {
default: {
name: “Simulated ES Module”,
sayHello() {
console.log(“Hello from simulated ESM”);
},
},
};

// main.js
const myModule = require(“./module3.js”).default;
console.log(myModule.name); // “Simulated ES Module”
myModule.sayHello(); // “Hello from simulated ESM”

在 ES6 模块中使用 module.exports

// module4.js
const myModule = {
name: “CommonJS in ESM”,
sayHello() {
console.log(“Hello from CJS in ESM”);
},
};

// 使用 ES6 的 `export default`
export default myModule;

// 兼容 CommonJS
export { myModule };

总结

  • 前端开发 (React, Vue, Webpack, Vite) → 使用 export default
  • Node.js(默认) → 使用 module.exports
  • 如果要兼容两者 → 需根据项目环境转换

在 Node.js 新项目中,推荐使用 ESM(即 import/export),因为它是未来的趋势。

作者 admin

百度广告效果展示