Split files, borrow parts

INPUT · Slides

Borrowing code someone else wrote

01 / 06

Someone has written that already

Laying out a date nicely. Putting commas into a number. Storing a password safely.

Jobs like these come up so often that someone in the world has already written them — and more often than not they have published the code for anyone to use, free. What would take you a day to write takes five minutes to borrow.

Being able to write it yourself matters, of course. But so does knowing when to borrow, so that you can spend your attention on the thing you actually want to build.

02 / 06

The package is the unit

Code that has been published comes bundled up in a unit called a package. What is inside is exactly what you have been writing: a set of files that export functions and classes.

Which means everything from the last lesson still applies. The only change is that what you pull in belongs to someone else instead of to you.

03 / 06

Really you fetch it with npm install

In real development you fetch a package from the terminal. Type the command below and it is downloaded into a folder called node_modules, ready to be called with import.

Being honest with you, though: Fulfledge runs entirely inside your browser, so it cannot run that command. On this screen you use packages that have been put in for you already.

Keep the steps in mind and use them when you develop on your own machine.

npm install greeting

04 / 06

The three that come with Fulfledge

These are the packages you can use in this material. All three are small things Fulfledge wrote for practice.

  • greeting … hand it a time of day and it gives you back a greeting
  • figures … tidies up how a number looks, adds a list of numbers up
  • letters … repeats text, reverses it, counts how long it is

They are not on the real npm, so searching for the names will turn up nothing. For practising how to use a package they are plenty.

05 / 06

Pull it in by its bare name

When you pull in a package you do not put ./ in front. You write just the name.

If there is a ./ it is one of your files; if there is not, it is a package. That way of telling them apart helps when you are reading other people's code, too.

// main.jsimport greeting from 'greeting';console.log(greeting("morning"));

Result

good morning

06 / 06

You need not read the inside

How a package is written inside is not your concern when you use it. All you want to know is what goes in and what comes out.

For greeting it goes like this.

  • hand it "morning" and you get good morning
  • hand it "noon" and you get hello
  • hand it "night" and you get good evening
  • hand it anything else and you get hey

Right then, let us pull it in and use it.