[CommonJS 模块 - require/exports] 和 [ES6 模块 - import/export] 的用法

4 篇文章 0 订阅

模块最大的好处是大大提高了代码的可维护性
使用模块还可以避免函数名和变量名冲突

JavaScript 现在有两种模块。一种是 ES6 模块,简称 ESM;另一种是 CommonJS 模块,简称 CJS
CommonJS 模块是 Node.js 专用的,与 ES6 模块不兼容。语法上面,两者最明显的差异是:

CommonJS 模块使用 require()module.exports
ES6 模块使用 importexport

  • require/exports 用法

    const fs = require('fs');
    exports.fs = fs;
    module.exports = fs;
    

    注:不可以直接对 exports 赋值,如 exports = { name: 'Hello', alia: 'World' }

    // /src/a.js
    module.exports = {
    	name: 'Hello',
    	alia: 'World'
    };
    // 等同于
    exports.name = 'Hello';
    exports.alia= 'World';
    
    // /src/b.js
    const aModule = require('./a');
    console.log('aModule:', aModule); // { name: 'Hello', alia: 'World' }
    

    module.exports 把函数作为模块的输出暴露

    // /src/a.js
    module.exports = function() {
    	return {
    		name: 'Hello',
    		alia: 'World'
    	};
    };
    
    // /src/b.js
    const aModule = require('./a')();
    console.log('aModule:', aModule); // { name: 'Hello', alia: 'World' }
    
  • import/export 用法

    import fs from 'fs';
    import { readFile } from 'fs'; // 从 fs 导入 readFile 模块
    import { default as fs } from 'fs'; // 从 fs 中导入使用 export default 导出的模块
    import * as fileSystem from 'fs'; // 从 fs 导入所有模块,引用对象名为 fileSystem
    import { readFile as read } from 'fs'; // 从 fs 导入 readFile 模块,引用对象名为 read
    
    export default fs;
    export const fs;
    export function readFile;
    export { readFile, read };
    export * from 'fs';
    
  • 模块加载方法

    .mjs 文件总是以 ES6 模块加载。
    .cjs 文件总是以 CommonJS 模块加载。
    .js 文件的加载取决于 package.json 中的 "type": "module" ,则会被解释成 ES6 模块。

    // package.json
    {
       "type": "module"
    }
    
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值