总结CommonJS和ES6使用模块化导出和导入的方法

引言

在前端项目中包含这大大小小的模块,我们需要经常使用模块导出导入功能,而关于导出和导入有两种方式:CommonJS和ES6. CommonJS是一种JavaScript模块化规范,它通常在服务端的Node.js环境中使用。每个模块都有自己的作用域、变量和方法,对其他模块不可见。ES6是JavaScript语言的下一代标准,在2015年6月发布。

CommonJS模块化

模块导出
在CommonJS中,使用module.exports关键字来导出模块。例如:

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}

module.exports = Person;

module.exports = module1Function;

模块导入
在CommonJS中,使用require函数来导入模块。例如:

const Person = require('./person');

多模块导出
同样用module.exports可以导出多个模块,例如:

class Person {
    constructor(name, age, gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
}

class Student extends Person {
    constructor(name, age, gender, grade) {
        super(name, age, gender);
        this.grade = grade;
    }
}

module.exports = {
    Person,
    Student
};

多模块导入

当用CommonJS导入多模块时,需要在require()之后加载具体的导出模块名,例如:

const Person = require('./person').Person;
const Student = require('./student').Student;

ES6模块化

模块导出
在ES6中,使用export关键字来导出模块。例如:

export class Person {
    constructor(name, age, gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
}

export default class Student extends Person {
    constructor(name, age, gender, grade) {
        super(name, age, gender);
        this.grade = grade;
    }
}

上面的例子中展示了ES6模块化导出的两种方式,第一种是普通地将class Person导出,在导入时需要使用大括号{Person}来表示具体导入的模块名;第二种是使用默认的导出方式,在导入时可以自定义使用的模块名来表示class Student,具体操作在模块导入中。

模块导入
使用ES6进行模块导入,根据模块导出的不同方式进行导入,例如:

import SuperStudent, { Person } from './person.js';
const john = new SuperStudent('John', 20, 'male', 100);
const kai = new Person('Kai', 24, 'male');

console.log(john)
console.log(kai)

在这个例子中使用了两种导入方式,第一种Student导入是对应的export default默认导出方式的导入,在使用默认导入时,命名可以自定义命名(像例子中的SuperStudent对应导出的Student),不过通常习惯使用默认导出的命名。第二种Person的导入是ES6多模块导入功能,需要使用大括号{}将多个模块包含起来。

同时,ES6还提供多模块自定义命名方法,例如:

import SuperStudent from './person.js';
import { Person as P } from './person.js';

const kai = new P('Kai', 24, 'male');

可以使用as对Person自定义命名为P

区别总结

语法差异:CommonJS使用module.exports和require语法,而ES6使用export和import语法。
默认导出:CommonJS没有默认导出功能,而ES6可以通过export default导出默认模块。
命名导出:CommonJS没有命名导出功能,而ES6可以通过export关键字导出多个模块,并在导入时使用具体的名称。
动态导入:CommonJS不支持动态导入,而ES6可以使用import()函数进行动态导入。
兼容性:由于Node.js默认使用CommonJS规范,因此在Node.js环境中使用ES6语法需要进行转译。而在现代浏览器中,原生支持ES6模块化规范。

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿黄勇闯天涯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值