Split files, borrow parts

INPUT · Slides

Split the files and join them up

01 / 05

Splitting alone does not work

Last lesson you cut things up by job. Next, try putting them in separate files.

There is a snag the moment you do, though. The name of a function written in one file cannot be seen from the other. Calling things by name worked until now because they were inside the same file.

What you use for this is export and import — the one that sends out and the one that pulls in.

02 / 05

Sending out: export default

Write export default in front of the thing you want to send. It means "this is what I hand outside as this file's representative".

That is all you write. Two words added to a function definition like any other.

// message.jsexport default function message() {  console.log("welcome");}

03 / 05

Pulling in: import

The catching side writes import name from './filename'. It goes at the very top of the file.

Once it is in, you call it exactly like a function written in your own file.

// main.jsimport message from './message.js';message();

Result

welcome

04 / 05

The catching side decides the name

export default is the way of sending out one "unnamed representative". So the side pulling it in can give it any name it likes.

Catch it as hello, as below, and the same function still runs. That said, it confuses readers, so keeping the original name is usually the recommendation.

import hello from './message.js';hello();

Result

welcome

05 / 05

Running starts at main.js

From here on, the exercises put file tabs above the editor. Tap to switch and write the contents of each.

When you press run, the one that starts moving is always main.js. The flow goes like this.

  • the import in main.js loads the other file
  • the contents of the loaded file run first
  • then the rest of main.js runs

Right — let us join two files up.