Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - Module Basics

ES6 (ECMAScript 6) has introduced a mechanism that allows us to build modules natively in JavaScript. We do that with two new keywords, import and export.

  • Export is the keyword we use to create the module and make is consumable
  • Import is the keyword that lets us consume that module
  • Both Import and Export expect a list of items to import/export within a set of { }.
  • Most modern browsers can use modules now but you need to set the type as module

The import and export keywords allow us to encapsulate our code into a single protected entity. This allows us to control access to the code within too.

We can and will reference our own dependencies internally. We can use it as-needed to keep scope to a minimum.

Module considerations:

  • Modules are singletons - when you export something from a module, every other thing that imports that module gets the same instance of it.
  • Items exported are not just values, they're pointers - they are bound. if something is exported and then changed, it changes everywhere.
  • Exports are static - you can't change it later at run time. Once it's loaded, it stays how it is. They are static
  • One module per file - seems like common sense. Modules are filed-based.
  • Module Bundler - depending on your implementation, you may need a like webpack. It will consolidate them all down into one file.