Modern JavaScript and a project · Lesson 44 of 45
Modules: import and export
Split code into small files, each doing one job.
7 minutes2 games
Real projects split code across files. Each file is a module that exports what others may use, and other files import it. There are named exports (many per file) and one default export.
JavaScript
// math.js
export const PI = 3.14159
export function area(r) {
return PI * r * r
}
export default function greet(name) {
return `Hi ${name}`
}
// app.js
import greet, { area, PI } from "./math.js"
import * as MathTools from "./math.js"
console.log(greet("Ali"), area(2), MathTools.PI)HTML
<!-- in the browser, mark the script as a module --> <script type="module" src="app.js"></script>
math.js: export
app.js: import
tools like Vite bundle them for the site
Complete the code
Import the sum function from ./utils.js.
{ sum } "./utils.js"
Quick question
What does import greet from "./math.js" bring in?
Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.