Import and Export in More Detail
The Big Idea
There are two main ways to export from a module: named exports and default exports. Knowing when to use each makes your code easier for others to use.
Your Roadmap
| Section | Time | Required? |
|---|---|---|
| Named exports | 15 min | ⚑ Required |
| Default exports | 15 min | ⚑ Required |
| Extra Resources | — | ◎ Optional |
Named exports
Use named exports when a module exports multiple values — each needs its own name.
Option 1 — export at the bottom:
const apple = 'Crispy red sphere'const banana = 'Squishy yellow crescent'function peel(fruit) {return 'beige lumps'}export { apple, banana, peel }
Option 2 — export inline (more common):
export const apple = 'Crispy red sphere'export const banana = 'Squishy yellow crescent'export function peel(fruit) {return 'beige lumps'}
Importing named exports:
import { apple, banana } from './fruits.js'console.log(`We have one ${apple} and one ${banana}`)
Importing as a namespace (avoids name conflicts between modules):
import * as Fruits from './fruits.js'import * as Stocks from './stocks.js'console.log(`I had a delicious ${Fruits.apple} for breakfast`)console.log(`I put all my money into ${Stocks.apple}`)
Default exports
Use a default export when a module has one main thing to expose.
// hype-the-crowd.jsexport default function hypeTheCrowd(call, response) {console.log(`When I say ${call}, you say ${response}!`)console.log(`ME: ${call.toUpperCase()}!`)console.log(`CROWD: ${response.toUpperCase()}!`)console.log(`ME: I can't hear you!`)}
Importing a default — no curly braces:
// main.jsimport hypeTheCrowd from './hype-the-crowd.js'hypeTheCrowd('cheese', 'cake')
You can name a default import whatever you like. Convention is to use the same name as the function, but JavaScript does not enforce this.
Extra Resources
These are optional. Use them if you want to go deeper.