Split files, borrow parts

INPUT · Slides

Calling what a package offers

01 / 05

Packages send things out by name too

greeting sent out just one thing with export default. But a package with several things to offer more often sends them out as named exports.

Pulling them in works exactly as it did with your own files. You just pick what you want with { }.

import { money } from 'figures';console.log(money(1200));

Result

$1,200

02 / 05

What is inside figures

  • money(number) … gives back a string in the shape $1,200
  • total(array) … gives back the sum of an array of numbers
  • round(number, digits) … gives back the number rounded to that many digits

You can hand a return value straight to another function. Below, the total is worked out first and then that number is tidied into money.

import { total, money } from 'figures';const prices = [300, 450, 120];console.log(money(total(prices)));

Result

$870

03 / 05

What is inside letters

  • repeat(text, count) … joins the text to itself that many times
  • reverse(text) … gives it back the other way round
  • count(text) … gives back how many letters there are

repeat is rather handy when you want to draw a dividing line. And try reverse on stressed — reading English backwards sometimes lands you somewhere lovely.

import { repeat, reverse } from 'letters';console.log(repeat("-", 3));console.log(reverse("stressed"));

Result

---
desserts

04 / 05

Writing them next to your own files

Pulling in a package and pulling in one of your own files can sit side by side. The ./ tells them apart, so it still reads fine when they are mixed.

There is no rule about the order, but a lot of people put packages first and their own files after. It shows where borrowed stops and homemade starts.

// data.jsexport default [980, 1500];// main.jsimport { money } from 'figures';import prices from './data.js';console.log(money(prices[0]));

Result

$980

05 / 05

Gather the places you use it into one

Where you use a package is best kept together in one file of your own, if you can manage it.

When you find a better package and want to switch, that one file is all you fix. Call it directly all over the place and you will be hunting them down one by one.

Borrowing is easy; remembering where you borrowed is your job. Right then, let us put some of them together.