Every exercise you’ve done in this course has asked you to keep each export, because it’s how the tests reach your code. The tests live in a file of their own, and they’ve been importing your functions from your file all along.
Priya’s page has outgrown one file. Its main.js keeps the guests, draws the page, and handles every click, in over a hundred lines.
In this lesson, you’ll split it into three files connected by imports like the ones the tests use. You’ll decide what each file shares and what it keeps to itself, and you’ll learn to read the errors caused by a broken import. Start by deciding which file should hold what.
Give Each File One Job
When you want to change how a row looks, you scroll past the records and the search to find drawRow(). A file that does three jobs makes every change start with a search. Priya’s code already falls into three jobs:
- The data:
players, the Still to come setting, and the code that changes them. - The drawing:
drawRow()andrender(), which turn the data into the page. - The wiring: The listeners that turn clicks into changes and redraws.
The data goes into state.js, the drawing into render.js, and the wiring stays in main.js. main.js is still the file that index.html loads, so it becomes the program’s entry point, the file where everything starts. It’ll be short, because the other two files do the work.
Each of these files will be a module, short for ES module or ECMAScript module. A module is a JavaScript file that shares names with export and takes them from other files with import.
Your main.js has been a module from the start, because index.html loads it with <script type="module">. That’s why the Console has never seen its names.
A module’s top-level names belong to that module alone. With one file, that only kept the Console out. With three files, every file has its own scope, so a name defined in one file is visible in another only when the first file exports it and the second imports it. Here’s an import you’ll write shortly:
scratch/render.js
import { players, settings } from "./state.js";
The braces list the names to take, spelled as the other file exports them. After from comes the path to that file, relative to the file doing the importing. The ./ means “in the same folder as me.”
Watch out: the path needs both its ./ and the full filename. Write "./state" without .js, and the browser asks the server for a file named state, which doesn’t exist. The Console shows a red 404 error for a URL that ends in /scratch/state, and the list stays empty. Write "state.js" without ./, and Chrome refuses it: