登峰造极境

  • WIN
    • CSharp
    • JAVA
    • OAM
    • DirectX
    • Emgucv
  • UNIX
    • FFmpeg
    • QT
    • Python
    • Opencv
    • Openwrt
    • Twisted
    • Design Patterns
    • Mysql
    • Mycat
    • MariaDB
    • Make
    • OAM
    • Supervisor
    • Nginx
    • KVM
    • Docker
    • OpenStack
  • WEB
    • ASP
    • Node.js
    • PHP
    • Directadmin
    • Openssl
    • Regex
  • APP
    • Android
  • AI
    • Algorithm
    • Deep Learning
    • Machine Learning
  • IOT
    • Device
    • MSP430
  • DIY
    • Algorithm
    • Design Patterns
    • MATH
    • X98 AIR 3G
    • Tucao
    • fun
  • LIFE
    • 美食
    • 关于我
  • LINKS
  • ME
Claves
长风破浪会有时,直挂云帆济沧海
  1. 首页
  2. Programming
  3. javascript
  4. 正文

Javascript es6 require/import/export 使用笔记

2022-08-25
参考链接: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;
  }
}
标签: 暂无
最后更新:2022-09-12

代号山岳

知之为知之 不知为不知

点赞
< 上一篇
下一篇 >

COPYRIGHT © 2099 登峰造极境. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

蜀ICP备14031139号-5

川公网安备51012202000587号