Default Exports
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 7 of 24.
store.js is about one thing, the store, and the file that imports it should not care what it is called inside.
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
Easy- Make
storethe default export ofstore.js. addsaves the note withstore.add(text)and printsAdding: 4. Buy bread.listprints every note in the store withformatNote.
Run node notes.js add Buy bread, then list: the new note is gone, because nothing is saved yet.
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
1Running JavaScript on Node
Hello, NodeCommand-Line ArgumentsCommands