Modules and npm
You'll learn to split code into files with export and import, and to add other people's code with npm.
import lines. An Expo app is your files plus packages from npm.Watch & read
Start with the required ones. The others are there when you need them.
Explanation
Your app grows. One file with 2,000 lines is hard to read. You want to keep money code in one file and screen code in another, and use one from the other. Each file that shares code this way is a module.
Think of a kitchen. The spice box is kept in one place. Any cook who needs salt goes and takes it from there, instead of keeping their own salt in every pot.
A file chooses what to share with export. Another file takes it with import:
// money.jsexport function formatTaka(amount) {return "Tk " + amount;}// app.jsimport { formatTaka } from "./money.js";console.log(formatTaka(500)); // Tk 500
There are two kinds of export. A named export (export function formatTaka) is imported with { }
and the exact same name. A file can also have one export default. You import that one without { },
and you may give it any name: import App from "./App";.
People often mix these up. If the file says export default, write no { }. If it says
export function or export const, use { } and match the name. The error you get is usually
"does not provide an export named …".
Now look at where the import comes from. A path that starts with ./ or ../ is your own file. A
bare name like "react" or "dayjs" is a package: code someone else wrote and shared.
Packages come from npm, a huge free library of JavaScript code. In the terminal, inside your project:
npm install dayjs
npm downloads the package into a folder called node_modules, and writes its name and version into
package.json, your project's shopping list. You never edit node_modules and you don't put it on
GitHub. Anyone who clones your project runs npm install once, and npm rebuilds it from package.json.
When you open a file, read the imports first. They tell you what the file uses and where each piece lives.
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1// money.js2export default function formatTaka(amount) {3 return "Tk " + amount;4}56// app.js7import { formatTaka } from "./money.js";8console.log(formatTaka(500));
Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3Which import comes from an npm package, not from your own file?
- 2 / 3
money.jshasexport function formatTaka(...). Which import works? - 3 / 3You clone a friend's project. It has
package.jsonbut nonode_modules. What do you do?
Explain it back
How confident are you with Modules and npm?
Done
import lines at the top of a file and say which come from your own files and which come from npm packages.