JSTAcademy
0 XP
Dashboard
Crash Courses
ES Modules & the Import/Export System
10 min
Masters+175 XP
Crash Courses · Masters

ES Modules & the Import/Export System

Organise code across files using named exports, default exports, and barrel patterns.
10 min read+175 XP on completionCert: JavaScript Crash Course
Tap any word in the text below to start reading from there.

ES Modules & the Import/Export System

A codebase is not one file. How modules work what is shared, what is private, how imports resolve is essential reading.

Named vs Default Exports

// Named exports — multiple per file
export function formatCurrency(amount) {
  return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount)
}
export const MAX_FILE_SIZE = 10 * 1024 * 1024

import { formatCurrency, MAX_FILE_SIZE } from './utils'
import { formatCurrency as fmt } from './utils'   // rename
import * as utils from './utils'                   // namespace
// Default export — one per file
export default function Button({ label, onClick }) {
  return <button onClick={onClick}>{label}</button>
}

import Button from './Button'      // name is your choice
import MyButton from './Button'    // also valid

Barrel Files

// components/index.ts
export { default as Button } from './Button'
export { default as Input } from './Input'
export { default as Modal } from './Modal'

// Consumer
import { Button, Input, Modal } from '@/components'

Dynamic Imports

// Load on demand
const { Chart } = await import('chart.js')

// Next.js dynamic with loading state
import dynamic from 'next/dynamic'
const Heavy = dynamic(() => import('./Heavy'), {
  loading: () => <Spinner />,
  ssr: false,
})

Path Aliases

// tsconfig.json
{ "compilerOptions": { "paths": { "@/*": ["./src/*"] } } }
import { Button } from '@/components'      // with alias
import { Button } from '../../../components'  // without — fragile

Module Scope is Private

// a.ts
const secret = 'only here'
export const shared = 'accessible via import'

// b.ts
import { shared } from './a'
// secret is inaccessible

A fundamental improvement over script tags where every variable was global.

0%