Start learning free

LESSON 121 OF 161 · FRONTEND: THE PROJECT AROUND THE CODE

import and export in JavaScript

Practice

In a Vite app every file is a module: what you declare in it stays inside the file. To let another file use something, you export it, and the other file imports it.

There are two kinds. A named export puts export before a declaration, and the importer asks for it by that exact name, in braces. A default export, export default value;, is the file's one main value, and the importer gives it any name it likes, without braces.

Here is the idea on another file:

// src/greet.js
const words = { hello: "Hi" };

export function greet(name) {
  return words.hello + ", " + name;
}

export default words;

// another file in src/
import words, { greet } from "./greet.js";

The path "./greet.js" starts with ./: the same folder as the importing file. A wrong name stops the page: a browser says The requested module '/src/greet.js' does not provide an export named ….

The Corner Shop's App.jsx got too long, so formatPrice moves into its own file, src/format.js, next to the shop's settings. App.jsx's import line is already written: import settings, { formatPrice } from "./format.js";. Opening the page must print:

> open the page
  screen:
    main
      heading 1: Corner Shop
      list
        item: Mug $12
        item: Notebook $7
        …
        item: Gift card $50
> what src/format.js exports
  formatPrice: a function
  default: an object with shopName, currency
> what src/App.jsx imports from "./format.js"
  settings (the default export): found
  { formatPrice } (a named export): found

Your task: in src/format.js, make the object settings with shopName "Corner Shop" and currency "$", write formatPrice(price) as a named export that returns the currency followed by the price, and make settings the default export.


Assignment
Follow the Coding Tutorial to write src/format.js: the shop's settings, the exported formatPrice function, and the default export that App.jsx imports.


Hint
export goes right before function. The default export comes last, once settings exists: export default and the value.


STEP 1 OF 6
    Ctrl + Enter to check

    Tools Modules in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free