Node: Export Import

Export

Let’s say we have a file called export.mjs.

export firstname = "Donald"
export lastname = "Trump"

export fullname = {firstname, lastname}

/*
  Up to this line is the same as saying:
  
  export {firstname, lastname, fullname}
*/

export default "John Doe"

Alternative export syntax with the same result as above:

firstname = "Donald"
lastname = "Trump"

export {firstname, lastname}

export fullname = {firstname, lastname}

/*
  Up to this line is the same as saying:
  
  export {firstname, lastname, fullname}
*/

export default "John Doe"

Import

Create a file called import.mjs:

import defaultname from './export.mjs'

console.log(defaultname)
=> John Doe
import {default as defaultname} from './export.mjs'

console.log(defaultname)
=> John Doe
import {firstname, lastname, fullname} from './export.mjs'

console.log(firstname)
=> Donald
console.log(lastname)
=> Trump
console.log(fullname)
=> { firstname: 'Donald', lastname: 'Trump' }
import {firstname as fName, lastname as lName, fullname as flName} from './export.mjs'

console.log(fName)
=> Donald
console.log(lName)
=> Trump
console.log(flName)
=> { firstname: 'Donald', lastname: 'Trump' }
import defaultname, {firstname, lastname, fullname} from './export.mjs'

console.log(defaultname)
=> John Doe
console.log(firstname)
=> Donald
console.log(lastname)
=> Trump
console.log(fullname)
=> { firstname: 'Donald', lastname: 'Trump' }
import * as Name from './export.mjs'

console.log(Name)
=> {
=>   default: 'John Doe',
=>   firstname: 'Donald',
=>   fullname: { firstname: 'Donald', lastname: 'Trump' },
=>   lastname: 'Trump'
=> }

console.log(Name.default)
=> John Doe
console.log(Name.firstname)
=> Donald
console.log(Name.lastname)
=> Trump
console.log(Name.fullname)
=> { firstname: 'Donald', lastname: 'Trump' }

References:


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *