Split files, borrow parts

INPUT · Slides

Send out several, each with a name

01 / 06

You want two out of one file

Adding and subtracting are both of the "calculation" family, so you want them in the same file. But export default was one per file.

What you use then is named exports: the way of sending out any number of things, each keeping its name.

02 / 06

Just put export on the front

Write export in front of the thing you want out. No default. That alone makes it visible from outside under that name.

// tools.jsexport function add(a, b) {  return a + b;}export function subtract(a, b) {  return a - b;}

03 / 06

Choose what to pull in with { }

The catching side writes the names it wants inside { }. What you do not use, you do not write.

In the example below subtract is also being sent out, but since it is not pulled in you cannot use it inside main.js. Bring in only as much as you need.

// main.jsimport { add } from './tools.js';console.log(add(3, 4));

Result

7

04 / 06

The name comes from the sending side

Unlike export default, with named exports the rule is that you catch it under the name it was sent as. Rewrite { add } as { addition } and it will not be found.

When pulling several in at once, line them up with commas. The line gets longer; what you are doing is the same.

import { add, subtract } from './tools.js';console.log(add(10, 4));console.log(subtract(10, 4));

Result

14
6

05 / 06

Values can have one too

export is not only for functions. Write export const name = value; and a value goes out with a name as well.

// shop.jsexport const shopName = "Broadbean Store";export const openHour = 9;

06 / 06

How to choose between them

  • export default … one leading part for the file. The catching side decides the name
  • named export … any number. The name comes through as it is

A file holding several tools takes named exports; a file holding one class takes default. That is roughly how the choice gets made.

Right — let us send some out with names.