Default Exports
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 8 of 33.
This lesson adds store.js, a file about one thing: the store that holds your notes. A file like that shares its one thing as its default export, and the file that imports it picks any name for it.
export default marks the one value a file is about. The importer gives it any name and writes no braces:
// config.js
const config = { port: 3000 };
export default config;
// app.js
import settings from './config.js';
console.log(settings.port);Braces ask for a named export, so import { config } from './config.js' fails here: config.js names nothing. Use a default export for a file's main value and named exports for a file of helpers.
Challenge
EasyYour notes need one place to live. The new file store.js holds them in a store object, which starts with three notes in store.notes. Share that store with notes.js, and use it in add and list.
- In
store.js, makestorethe file's default export. The comment at the bottom marks the spot. - In
notes.js, import the store at the top, next to theformatNoteimport. A default import has no curly braces. - In the
addbranch, add the note withstore.add(text). It returns the new note's number. PrintAdding:followed by the note, formatted with that number. The store starts with three notes, sonode notes.js add Buy breadprints:Adding: 4. Buy bread - In the
listbranch, keep theNotes for ...heading. Under it, replaceNo notes yetwith every note in the store, one per line, each formatted withformatNoteand numbered from 1.node notes.js listprints:If the store has no notes, still printNotes for you 1. Buy milk 2. Call Ada 3. Water the plantsNo notes yetunder the heading.
Try it: type add Buy bread in the box after $ node notes.js and press Enter. You see Adding: 4. Buy bread. Then type list: you see the three starting notes, but not Buy bread. The store lives in memory, so every run starts again from the three notes in store.js. Chapter 3 saves notes to a file.
Try it yourself
// The notes live here until chapter 3 saves them to a file.
const store = {
notes: ['Buy milk', 'Call Ada', 'Water the plants'],
add(text) {
this.notes.push(text);
return this.notes.length;
},
};
// Make store the default export of this file.
All lessons in Node.js Basics
Practice on your own: Express playground