Creating a Module

Let's start creating, importing, and exporting modules.

Simply put, in JavaScript, a module is an individual file that contains variables, constants, functions, and classes.

Modules follow the famous Vegas adage: “What happens in Vegas stays in Vegas.”

📍 Code within a module is executed in strict mode, so the variables within a module do not accidentally spillover to the global scope. You don’t need to specify 'use strict';.

A module’s author has to carefully choose what to export from the file to the outside world. All else is invisible and unreachable directly from the outside. Likewise, for a module to use something that’s not part of it, it has to import it first. Once imported, the reference becomes part of the current module’s scope.

Support for Modules

NodeJS, starting in version 8.5, provides experimental support for modules with the --experimental-modules command-line flag. NodeJS requires files that use modules to be named with the .mjs extension instead of .js. When you load an ES module, it might throw an experimental warning because ES modules are experimental.

The browser support for modules varies across browsers and versions. Tools like Babel may be used to transpile code with modules into traditional JavaScript code for execution on old browsers that don’t support modules.

Get hands-on with 1400+ tech skills courses.