Split files, borrow parts

INPUT · Slides

Sending values out of a file

01 / 05

It is not only functions that go out

What you write after export default need not be a function. Anything that is a value can go. A string, a number, an array, an object.

// shop.jsexport default "Broadbean Store";

02 / 05

Pulling it in is exactly the same

The catching side is written no differently from the function case. What comes in is an ordinary value, so you use it just as if it were sitting in a variable.

// main.jsimport shopName from './shop.js';console.log(shopName);

Result

Broadbean Store

03 / 05

Put gathered data outside

Keep an array or object in its own file and, when you want to change what is in it, you only open that file. No need to read the file with the work in it.

Giving the value a name before sending it out is also common. For a reader, a name makes it clearer what the data is.

// menu.jsconst menu = ["curry", "noodles"];export default menu;// main.jsimport menu from './menu.js';console.log(menu[0]);

Result

curry

04 / 05

One export default per file

export default is the way of sending out "this file's representative". So you can only write it once in a file. Write it twice and it errors, and that file cannot be loaded at all.

There are two moves when you have several things to send.

  • gather them into an object and send that as one
  • use the named exports you will learn next lesson
// settings.jsconst settings = {  name: "Broadbean Store",  open: 9,};export default settings;

05 / 05

The more it changes, the more it wants to be outside

If you are unsure what to put in its own file, start with the things that change easily. The product list, the prices, the wording of a greeting. The places you will rewrite over and over.

The work, once written correctly, you tend not to touch for a while. So sending the data you touch often outside means fewer files to open.

Right — let us send some values out and pull them back in.