Modules and Imports
Organizing code with ES modules
Introduction
In this lesson, you'll learn about modules and imports in JavaScript. Coming from Python, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Python, you're familiar with organizing code with es modules.
JavaScript has its own approach to organizing code with es modules, which we'll explore step by step.
The JavaScript Way
Let's see how JavaScript handles this concept. Here's a typical example:
// math_utils.js
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export class Calculator {}
export default class MainCalc {} // default export
// main.js
import { PI, add } from "./math_utils.js";
import * as mu from "./math_utils.js";
import Calc from "./math_utils.js"; // default import
import MainCalc, { PI as pi } from "./math_utils.js";
// Node built-ins
import fs from "fs";
import path from "path";Comparing to Python
Here's how you might have written similar code in Python:
# math_utils.py
PI = 3.14159
def add(a, b): return a + b
class Calculator: pass
# main.py
from math_utils import PI, add
import math_utils as mu
from math_utils import Calculator as Calc
# Standard library
import os
import json
from pathlib import PathYou may be used to different syntax or behavior.
JS requires explicit export — Python exports everything by default
You may be used to different syntax or behavior.
Default exports have no Python equivalent
You may be used to different syntax or behavior.
import * as ns ≈ import module_name
You may be used to different syntax or behavior.
File extensions usually required in browser/ES modules
Step-by-Step Breakdown
1. Named Exports and Imports
JavaScript requires explicit export. Named imports use curly braces.
# Everything in a .py file is importable
from utils import add, PI// Must mark as export
export function add() {}
export const PI = 3.14;
// Import:
import { add, PI } from "./utils.js";2. Default Exports
Each module can have one default export, imported without curly braces.
# No direct equivalent in Pythonexport default class App {}
// Import:
import App from "./app.js";3. Namespace Import
import * as ns gives access to all named exports under one namespace.
import math_utils as mu
mu.add(1, 2)import * as mu from "./math_utils.js";
mu.add(1, 2);Common Mistakes
When coming from Python, developers often make these mistakes:
- JS requires explicit export — Python exports everything by default
- Default exports have no Python equivalent
- import * as ns ≈ import module_name
Key Takeaways
- export required — nothing is auto-exported
- import { name } for named, import X for default
- import * as ns for namespace import