Type something to search...
Part 1, Getting Started with Modules

Part 1, Getting Started with Modules

Introduction

Before ES6, JavaScript did not have a native module system, which made it difficult to split large codebases into manageable pieces. Developers relied on patterns like the Module Pattern, or third-party libraries such as RequireJS or CommonJS, to organize code into reusable components. However, with ES6, JavaScript introduced native module support, giving developers a clean and efficient way to manage dependencies and organize code.

In this section, we’ll start with the fundamental concepts of importing and exporting in ES6, laying the foundation for more advanced topics later on.

What is a Module?

A module in JavaScript is simply a file containing reusable code. Each module can define variables, functions, objects, or classes and expose them to other modules using the export statement. Modules also keep code isolated, meaning variables and functions declared inside a module are not accessible to the global scope, unless explicitly exported.

For example, imagine you have a file math.js where you define a function to add two numbers:

// math.js
export function add(a, b) {
  return a + b;
}

The function add is now available for other modules to use, but only if they explicitly import it.


Basic export Syntax

There are two main ways to export from a module in ES6: named exports and default exports. In this part, we’ll focus on named exports.

Named Exports

A named export allows you to export multiple variables or functions from a module. Each item must be explicitly named in both the export and the corresponding import. Here’s how it works:

// utilities.js
export const pi = 3.14159;
export function multiply(x, y) {
  return x * y;
}

You can export as many items as needed from the module. When importing them into another file, you specify the exact names of the exports you want to use:

// app.js
import { pi, multiply } from './utilities.js';

console.log(multiply(pi, 2)); // Output: 6.28318

In this example, pi and multiply were exported from utilities.js and then imported into app.js. You must use the same names when importing named exports.


Basic import Syntax

The import statement is used to bring in variables, functions, objects, or classes from another module. As seen above, you use curly braces {} to specify named exports:

import { export1, export2 } from 'module';

You can also rename imported items using the as keyword, which can be useful if there are naming conflicts or if you want to give them more meaningful names:

import { multiply as mult } from './utilities.js';

console.log(mult(5, 6)); // Output: 30

Default Exports

Sometimes, you may want to export a single value as the default export. A default export is useful when a module only provides one main functionality or object, making it easier to import without specifying a name. Here’s how it works:

// math.js
export default function subtract(a, b) {
  return a - b;
}

You can import a default export without using curly braces:

// app.js
import subtract from './math.js';

console.log(subtract(10, 5)); // Output: 5

Default exports are common for modules where there is one primary function or object. They help make your imports cleaner and reduce boilerplate.


Combining Named and Default Exports

It is possible for a module to use both named and default exports. For example:

// math.js
export const pi = 3.14159;
export default function add(a, b) {
  return a + b;
}

You can import both like this:

// app.js
import add, { pi } from './math.js';

console.log(add(pi, 2)); // Output: 5.14159

In this case, add is the default export, and pi is a named export.


Exporting As You Declare

You can also export variables or functions as you declare them, without repeating the export keyword:

export const name = 'John';
export function greet() {
  console.log('Hello, ' + name);
}

Or combine everything into a single export at the end of the file:

const name = 'John';
function greet() {
  console.log('Hello, ' + name);
}

export { name, greet };

Importing Entire Modules

In some cases, you may want to import everything from a module under a single namespace. This is useful for larger modules with many exports:

// utilities.js
export const pi = 3.14159;
export function multiply(x, y) {
  return x * y;
}
export function divide(x, y) {
  return x / y;
}

Instead of importing each export individually, you can import the whole module under an alias:

// app.js
import * as utils from './utilities.js';

console.log(utils.multiply(3, 4));  // Output: 12
console.log(utils.pi);              // Output: 3.14159

Here, the entire module is imported as the utils object, and you can access each export as a property of that object.


Recap

In Part 1, we’ve covered:

  • What modules are and why they are important.
  • The basic syntax for exporting and importing in JavaScript ES6.
  • Named exports, default exports, and how to import them.
  • Combining named and default exports.
  • Importing an entire module under an alias.

In the next part, we’ll delve deeper into the differences between named and default exports, including best practices for choosing between them and more detailed examples to solidify your understanding.

Share :

Related Posts

Horizontal Scaling in Kubernetes

Horizontal Scaling in Kubernetes

Horizontal scaling in Kubernetes refers to dynamically adjusting the number of application instances (pods) based on workload changes to maintain optimal performance. Unlike vertical scaling, which in

read more
How to Use Docker for Development Environments

How to Use Docker for Development Environments

When developing an application running in Docker, you can edit the files on your local machine and have those changes immediately reflected in the running container. This is typically done using Docke

read more
CLI pager commands - more, less, and most

CLI pager commands - more, less, and most

These PAGER commands allow you to navigate through file and data stream content with a variety of useful commands. If you need to manually visually navigate through a lot of text or data, you'll f

read more
Defining New ASCII Designs For Thomas Jensens Boxes Software

Defining New ASCII Designs For Thomas Jensens Boxes Software

The "Boxes" command line tool takes a block of text and wraps it in one of 50 some frames listed with boxed -l and specified by the user with boxes -d the text can either be piped into boxed or a

read more
Javascript ES6 Modules, Introduction

Javascript ES6 Modules, Introduction

With the release of ECMAScript 2015 (ES6), JavaScript introduced a powerful new feature: modules. This addition was a significant shift in how developers structure and manage code, allowing for better

read more
Understanding JavaScript Promises

Understanding JavaScript Promises

In JavaScript, the concept of thenables often arises when working with Promises. Promises inherit from the base class Thenable, meaning that Promises are a type of Thenable, but a Thenable is not

read more
Part 4, Dynamic Imports and Lazy Loading

Part 4, Dynamic Imports and Lazy Loading

Introduction So far, we’ve explored the world of static imports in JavaScript, where dependencies are imported at the start of a script’s execution. However, in modern web development, there are c

read more
Understanding JavaScript Promises and Lazy Loading Callbacks

Understanding JavaScript Promises and Lazy Loading Callbacks

In JavaScript, thenables play a key role in asynchronous programming, particularly with Promises in ES6. One of the advantages of ES6 Promises (which use thenables) over older implementations like

read more
Part 2, Understanding Named and Default Exports

Part 2, Understanding Named and Default Exports

Introduction In the previous part, we introduced the basics of importing and exporting in JavaScript ES6, covering both named and default exports. Now, it’s time to explore these t

read more
Part 3, Re-exports and Module Aggregation

Part 3, Re-exports and Module Aggregation

Introduction As projects grow, the number of modules and dependencies can quickly become overwhelming. In large codebases, managing and organizing these modules is key to maintaining readability a

read more
Managing Multiple Git Identities Per Single User Account

Managing Multiple Git Identities Per Single User Account

If you need to work make changes to code under different identities, there are a few different ways you can approach this. The first solution I saw on many webpages was way too clunky for my taste. It

read more
Secure Authentication & Authorization Exercises

Secure Authentication & Authorization Exercises

Each exercise includes:Scenario Initial Information Problem Statement Tasks for the student Bonus Challenges for deeper thinking**Section 1: OAuth 2.0 + PKCE

read more
Never Been a Huge Fan of IDEs, but I Like Visual Studio Code

Never Been a Huge Fan of IDEs, but I Like Visual Studio Code

To be completely honest, for the past many years, I've debated whether or not to use an IDE. On one had, they provide a number of features like code completion, debugging, and a number of other things

read more
Powerful Text Selection Operations in VSCode

Powerful Text Selection Operations in VSCode

VSCode has become one of the most popular IDEs in recent years. It is also available for free. Here are a few text selection options of which you may not be aware. Multiple Selections It is possi

read more
Visual Studio Code - Creating a Custom Text Filter Extension

Visual Studio Code - Creating a Custom Text Filter Extension

In this post I will describe a way to create an extension which allows the user to receive the selected text as a string passed into a Typescript function, run that string through any command line pro

read more
What is Docker and Where and Why Should You Use it?

What is Docker and Where and Why Should You Use it?

Docker is a platform designed for containerization, allowing developers to package applications and their dependencies into lightweight, portable containers. These containers are isolated environments

read more
What is Kubernetes? Where and Why Should You Use it?

What is Kubernetes? Where and Why Should You Use it?

Key Use Cases and Benefits Kubernetes simplifies the deployment and scaling of applications through automation. It facilitates automated rollouts and rollbacks, ensuring seamless updates without d

read more
Secrets Management DevOps Tools and More

Secrets Management DevOps Tools and More

These tools provide a means of securely storing secrets (encryption keys, passwords, all that good stuff that you want to make available to your production systems, but you must protect from exposure)

read more
Web Application Boilerplate

Web Application Boilerplate

I've been tinkering with a number of projects and along the way I've come up with what I think is a solid starting point for any web application that you might build. Understanding that your applicat

read more
Part 5, Best Practices and Advanced Techniques

Part 5, Best Practices and Advanced Techniques

In the previous parts of this series, we explored the fundamentals of module importing and exporting in ES6, the different ways to define modules, and how to work with default and named exports. In th

read more
Using Makefiles, SOPS, and virtualenv Together for Elegant Python Environments

Using Makefiles, SOPS, and virtualenv Together for Elegant Python Environments

I've been managing my secrets with sops ever since I looked into the subject last month, and I've been using Makefiles to handle bringing up my docker environments as they provide a nice way to not

read more