DEV Community

Cover image for (Javascript) My learning journey: Modules Import/Export
Eric The Coder
Eric The Coder

Posted on

(Javascript) My learning journey: Modules Import/Export

If you want to miss nothing click follow and you are welcome to comments and discuss with me.

Without further ado here is a summary of my learning notes for today.

Modules

Modules is a reusable piece of code store into a standalone file. Putting modules together we can build a complex application.

Module in Javascript:

  • All variables are scope/private to module
  • To use other modules variables we need to use import
  • To expose/share variables to other modules we need to use export
  • Module are load in asynchronous mode
  • Module always run in strict mode
  • this keyword at top level is undefined

Module creation exemple (index.html)

<script type="module" defer src="main.js">
</script>
Enter fullscreen mode Exit fullscreen mode

Name Export
To use name export simple put export keyword in front of variables or functions you want to export

export const message = 'Hello World'
// or after declaration
const hello = 'Hello World'
const bye = 'Bye World'
export { message, bye }
// Also possible to use alias 
export { message as msg, bye } 
Enter fullscreen mode Exit fullscreen mode

Import
Import are not a variables copy they are live connection to that variable.

// import the module 
import './display.js'
// import specific export
import { message } from './display.js'
// multiple import and alias
import { message, bye as goodBye } from './display.js'
// import all export im one object
import * as display from '/.display.js'
// use import object
console.log(display.message)
Enter fullscreen mode Exit fullscreen mode

Default Export

export default function() {
  console.log('Hello World')
}
Enter fullscreen mode Exit fullscreen mode

Import (default export)

import hello from './display.js'
Enter fullscreen mode Exit fullscreen mode

CommonJS Module

Use in NodeJS

// Export
export.display = function() {
  console.log('Hello World')
}

// import
const { display } = require('./display.js')
Enter fullscreen mode Exit fullscreen mode

Discussion (1)