Web Development courseLesson 11 of 20 · tap to see all lessons
Web Development · Beginner
JavaScript Modules and Tools: import and export, Node.js, npm, Packages, Scripts, and async
Split JavaScript into modules with import and export, run it with Node.js, install packages with npm, add scripts to package.json, and review async code and fetch.
- Qyubie Learn Editorial Team
- Published
- 15 min read
Includes 2 exercises and 3 quick checks you can do right here.
Up to now, each JavaScript example lived in one <script> tag. Real apps have hundreds of files and use code other people wrote. This lesson gives you the tools for that: modules to split code into files, Node.js to run JavaScript outside the browser, and npm to install packages and run project scripts. React and Next.js, in the next three lessons, are built entirely on these tools. The lesson ends with a review of async code, which every app that loads data needs.
By the end of this lesson you will be able to:
- split code into modules with
exportandimport, - organize a small project into files and folders,
- explain what Node.js and npm are, and run JavaScript with Node,
- create a project with
package.json, install a package, and add scripts, and - write async code with promises,
async/await, andfetch.
Why modules
Picture one script.js with 3,000 lines: every variable can clash with every other, and nobody can find anything. A module is simply a JavaScript file that keeps its variables to itself and chooses what to share:
exportmarks what other files may use.importbrings in what another file exported.
Everything not exported stays private to its file. That makes each file small, focused, and safe to change.
export and import
Here's a small project split into three files. grades.js holds grade logic and exports three things by name:
// src/grades.js
export const PASSING = 75;
export function average(grades) {
const total = grades.reduce((sum, g) => sum + g, 0);
return total / grades.length;
}
export function remark(grade) {
return grade >= PASSING ? "Passed" : "Failed";
}format.js has one main job, so it uses a default export:
// src/format.js
export default function formatGrade(value) {
return value.toFixed(1);
}main.js imports from both:
// src/main.js
import formatGrade from "./format.js";
import { average, remark, PASSING } from "./grades.js";
const grades = [88, 92, 71, 85];
const avg = average(grades);
console.log(`Average: ${formatGrade(avg)}`);
console.log(`Remark: ${remark(avg)} (passing is ${PASSING})`);Running node src/main.js (you'll set that up below) prints:
Average: 84.0
Remark: Passed (passing is 75)The two kinds of export:
| Named export | Default export | |
|---|---|---|
| Write | export function average() {} | export default function formatGrade() {} |
| Import | import { average } from "./grades.js" | import formatGrade from "./format.js" |
| How many per file | as many as you like | at most one |
| Name when importing | must match (or rename with as) | any name you choose |
A few more forms you'll see:
import { average as mean } from "./grades.js"; // rename on import
import * as grades from "./grades.js"; // everything, as grades.average, grades.PASSING
import validator from "validator"; // a package from npm (no ./)The path tells JavaScript where to look. ./ or ../ means a file in your project; a bare name like "validator" or "react" means an installed package.
Modules in the browser
Browsers load modules with type="module":
<script type="module" src="src/main.js"></script>Module scripts run after the page is parsed (like defer), and they work only when the page is served over http://, not opened as a file. That's one reason modern projects use a development server, which you'll get from npm.
The runnable examples on this site run one block at a time, so they can't import your own files, but a module script can import a package straight from a CDN. This page imports the chunk function from the lodash package to split a class into groups of three:
Try it · HTML & CSS
Organizing code
There's no single correct layout, but these habits keep projects readable:
- One job per file.
grades.jscalculates,format.jsformats,main.jsputs them together. - Group by feature or type in folders:
src/components/,src/lib/,src/pages/. - Name files after what they export:
formatGradelives informat.jsorformatGrade.js. - Keep the entry file short. It should read like a summary of the app.
grade-app/
├── package.json
├── package-lock.json
├── node_modules/ ← installed packages (never edit, never commit)
└── src/
├── main.js ← entry point
├── grades.js
├── format.js
└── check-email.jsQuick check
Node.js: JavaScript outside the browser
Node.js is a program that runs JavaScript on your computer or a server, using the same engine as Chrome. In Node there's no document or window (there's no page), but you can read files, start web servers, and run tools. Almost every modern web tool, including React's and Next.js's build tools, runs on Node.
Install the LTS version from nodejs.org, then check it in a terminal:
node -v
npm -vBoth print a version number. To run a file, give Node its path:
node src/main.jsnpm: packages and project setup
npm (Node Package Manager) comes with Node. It does two jobs: it installs packages (code published by others, from the npm registry) and it runs your project's scripts.
Start a project
mkdir grade-app
cd grade-app
npm init -y
npm pkg set type=modulenpm init -y creates package.json, the file that describes your project. It starts with "type": "commonjs" (Node's older module style, which uses require); npm pkg set type=module changes it to "module", which tells Node that .js files in this project use import/export.
Install a package
Checking emails by hand is easy to get wrong, so use a well-tested package instead:
npm install validatornpm downloads it into node_modules/, records it in package.json under dependencies, and writes package-lock.json, which pins the exact versions so every teammate installs the same code. Now use it:
// src/check-email.js
import validator from "validator";
const emails = ["ana@example.com", "ben@", "cara.santos@school.edu.ph"];
for (const email of emails) {
console.log(email, validator.isEmail(email) ? "valid" : "invalid");
}Scripts
The scripts section of package.json gives names to commands, so everyone runs the project the same way. After adding two scripts (with npm pkg set scripts.start="node src/main.js", or by editing the file), the important parts look like this:
{
"name": "grade-app",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "node src/main.js",
"check": "node src/check-email.js"
},
"dependencies": {
"validator": "^13.15.35"
}
}Run a script with npm run:
npm run checkana@example.com valid
ben@ invalid
cara.santos@school.edu.ph valid(start and test are special: npm start works without run.) In React and Next.js projects you'll use npm run dev to start the development server and npm run build to make the production version.
Commands you'll use every day
| Command | What it does |
|---|---|
npm install | install everything listed in package.json (run after cloning a project) |
npm install name | add a package to dependencies |
npm install -D name | add a package to devDependencies (tools needed only while developing) |
npm uninstall name | remove a package |
npm run name | run a script from package.json |
npx name | run a package's command without installing it into the project |
Two rules for Git
-
Never commit
node_modules/. It can hold thousands of files, and anyone can recreate it withnpm install. Add it to.gitignore:node_modules/ -
Do commit
package.jsonandpackage-lock.json. Together they let teammates install exactly the same versions.
Quick check
Async JavaScript review
Some work takes time: loading data, reading a file, waiting for a timer. JavaScript doesn't stop and wait; it starts the work and gets a promise, an object that will later hold the result (or an error). async/await lets you write that code top to bottom.
Here getStudent pretends to be a slow server: it waits 300 milliseconds, then returns a student or throws an error:
Try it · JavaScript
Output:
Loading...
Ben
Problem: Student 9 not foundThe rules:
- An
asyncfunction always returns a promise, even when youreturna plain value. awaitpauses that function (not the whole page) until the promise settles, then gives you the value.- A rejected promise throws at the
await, so you handle it withtry/catch.
Many at once with Promise.all
await inside a loop runs requests one after another. When they don't depend on each other, start them all and wait for all of them together:
Try it · JavaScript
Output:
[92,74,85]
Highest: 92The three waits overlap, so this takes about 200 ms instead of 600. Promise.all keeps the results in the same order as the input, and rejects if any one of them fails.
fetch, one more time
fetch returns a promise, so everything above applies. This reusable helper is a pattern you'll use in React: it checks the status, reads JSON, and turns a bad status into an error:
Try it · JavaScript
Output:
Leanne Graham
Request failed: 404Quick check
Exercise · JavaScript
Load students in order
Use await with getStudent to print the names of students 1, 2, and 3, one per line, then Done.
Expected output
Ana Ben Cara Done
Hint
for (let id = 1; id <= 3; id++) { const s = await getStudent(id); console.log(s.name); } then console.log("Done").
Show a solution
Try it yourself first — you learn more from a wrong attempt than from reading an answer.
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function getStudent(id) {
await wait(100);
return { id, name: ["Ana", "Ben", "Cara"][id - 1] };
}
for (let id = 1; id <= 3; id++) {
const student = await getStudent(id);
console.log(student.name);
}
console.log("Done");
Exercise · JavaScript
Class total with Promise.all
Get the scores of all three students at the same time with Promise.all, then print the total as Total: 251.
Expected output
Total: 251
Hint
const scores = await Promise.all(names.map((n) => getScore(n))); then add them with reduce.
Show a solution
Try it yourself first — you learn more from a wrong attempt than from reading an answer.
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function getScore(name) {
await wait(150);
return { Ana: 92, Ben: 74, Cara: 85 }[name];
}
const names = ["Ana", "Ben", "Cara"];
const scores = await Promise.all(names.map((n) => getScore(n)));
const total = scores.reduce((sum, s) => sum + s, 0);
console.log(`Total: ${total}`);
Common mistakes
- Leaving out
.jsin a relative import ("./grades"). Browsers and Node's module mode need the full file name. (Build tools like Next.js add it for you.) - Using braces for a default export, or no braces for a named one.
- Leaving
"type": "commonjs"(thenpm initdefault), which gives "Cannot use import statement outside a module" in Node. Set it to"module". - Committing
node_modules/. - Forgetting
await, then gettingPromise { <pending> }instead of the value. - Not checking
response.ok.fetchdoesn't throw on a 404 or 500.
Summary
- A module is a file that shares only what it
exports. Named exports use braces when imported; a default export doesn't. - Node.js runs JavaScript outside the browser; npm installs packages and runs scripts.
package.jsondescribes the project, its dependencies, and its scripts;package-lock.jsonpins exact versions;node_modules/stays out of Git.asyncfunctions return promises;awaitwaits for them;try/catchhandles failures;Promise.allruns independent work at the same time.
Next: React, where you'll build pages out of reusable components, using everything from this lesson.