JavaScript/ES6 Module/Export Examples

Sep 24, 2020

JavaScript Module

Edit TestModule.js

// local usage, not exportedfunction print(str) {  console.log(str)}// enumconst FruitType = Object.freeze({  CITRUS: 1,  TROPICAL: 2,  MELONS: 3})// classclass Fruit {  constructor(name, type) {    this.name = name    this.type = type  }  get fullName() {    return `${this.name}, type=${this.type}`  }  print() {    print(this.toString())  }}// functionfunction tell(name) {  print(`This is ${name}`)}// named exportexport {  Fruit, FruitType, tell}

You can export directly as well

// local usage, not exportedfunction print(str) {  console.log(str)}// enumexport const FruitType = Object.freeze({  CITRUS: 1,  TROPICAL: 2,  MELONS: 3})// classexport class Fruit {  constructor(name, type) {    this.name = name    this.type = type  }  get fullName() {    return `${this.name}, type=${this.type}`  }  print() {    print(this.toString())  }}// functionexport function tell(name) {  print(`This is ${name}`)}

Use default exports to interoperate with existing CommonJS and AMD module systems

export default function tell(name) {  print(`This is ${name}`)}

or

export default {  Fruit, FruitType, tell}

You could renamed export

export {  tell as show,  Fruit,   FruitType}

Import Module

import { FruitType, Fruit, tell } from './TestModule.js'const fruit = new Fruit('Watermelon', FruitType.MELONS)tell(fruit.fullName)

NOTE: JavaScript Import Examples

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.