参考链接:https://bobbyhadz.com/blog/javascript-export-class
module.exports和exports是属于commonJs规范,export和export default是ES6模块规范。
exports 等于 module.exports,相当于在js文件头部,有一个module对象,module.exports = exports;
exports是一个对象,所以可以exports多个值
export
export default
export default 可以设置本JS文件默认导出的对象,每个文件仅允许一个export default:
// 👇️ default export
export default class Employee {
constructor(id, name, salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
increaseSalary() {
this.salary += 100;
}
}
// 👇️ named export
export class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
其它文件中导入这两个类:
// 👇️ default and named imports
import Employee, {Person} from './another-file.js';
const emp = new Employee(1, 'Alice', 100);
console.log(emp.id); // 👉️ 1
console.log(emp.name); // 👉️ "Alice"
const person = new Person('Bob', 30);
console.log(person.name); // 👉️ "Bob"
export class
普通用法
// 👇️ named export
export class Employee {
constructor(id, name, salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
increaseSalary() {
this.salary += 100;
}
}
export 单行使用
class Employee {
constructor(id, name, salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
increaseSalary() {
this.salary += 100;
}
}
// 👇️ named export (same as previous code snippet)
export {Employee};
一个文件多个class
// 👇️ default export
export default class Employee {
constructor(id, name, salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
increaseSalary() {
this.salary += 100;
}
}
// 👇️ named export
export class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}