在实际项目开发的过程中,肯定都会使用导入导出的功能,它允许我们将代码分割成小的、独立的模块,每个模块负责特定的功能或任务。
下面就简单介绍几种模块导入导出方式
CommonJS 模块导出
使用exports(module.exports)、require
这是一种CommonJS模块系统的导入导出方式。CommonJS 最初是 Node.js 采用的模块系统,主要特点是同步加载模块。它使用 module.exports 导出模块,和 require() 导入模块。
导出
// 模块定义
// module.js
const data = [1, 2, 3];
function multiplyBy2(arr) {
return arr.map(num => num * 2);
}
module.exports = {
data,
multiplyBy2,
};
// 或者直接使用 exports 导出
exports.data = data;
exports.multiplyBy2 = multiplyBy2;
导入
// 主程序
// app.js
const { data, multiplyBy2 } = require('./module');
console.log(data); // [1, 2, 3]
console.log(multiplyBy2(data)); // [2, 4, 6]
ES Modules
ES Modules中常用的是具名导出和默认导出两种方式
具名导出
使用 export 关键字可以导出多个具名的变量、函数或类。具名导出允许我们在导入时使用相同的名称来引用导出的内容。
导出
// 模块定义
// module.mjs (ES Module 文件需要使用 .mjs 扩展名)
export const data = [1, 2, 3];
export function multiplyBy2(arr) {
return arr.map(num => num * 2);
}
导入
// 主程序
// app.mjs
import { data, multiplyBy2 } from './module.mjs'; // 导出时使用什么名字导入也要使用相应名字
console.log(data); // [1, 2, 3]
console.log(multiplyBy2(data)); // [2, 4, 6]
默认导出
默认导出允许我们从模块中导出一个单独的值。在 ES Modules 中,使用 export default 关键字可以导出默认值,而在导入时我们可以为其指定任何名称。
导出
// 模块定义
// module.mjs
const data = [1, 2, 3];
export default data;
导入
// 主程序
// app.mjs
import myData from './module.mjs'; // 可以更改任何合法的变量名
console.log(myData); // [1, 2, 3]
结语
- Node.js 12 及以上版本:如果你的 Node.js 版本支持 ES Modules(通常是 Node.js 12
及以上),并且项目不依赖于大量的 CommonJS 模块,推荐使用 ES Modules。 - 浏览器应用:无论是现代的前端应用还是桌面应用,通常都应该使用 ES Modules,因为它是未来 JavaScript 的标准。
- Node.js 旧版和传统项目:如果你的项目需要兼容旧版的 Node.js,或者大量依赖于 CommonJS 模块,可以继续使用
module.exports 和 require()。
综上所述,选择使用 module.exports 还是 ES Modules 取决于项目的环境和需求。对于新项目和现代化的 JavaScript 开发,推荐使用 ES Modules,它能提供更好的模块化支持和未来的兼容性。