30 Days Of JavaScript

Day 29: Mopping up

Lesson 1: Modules 1

So far all of our JavaScript has been written in one file.

Sure, our PokeDex included code via a third party with that long URL, other than that all our code has been in a single file.

This is fine with small projects, however for larger projects we split our code in to many files making them easier to manage.

One of our projects it's actually ripe for this, the Banish Boredom one. So let's dive in and split the code up a little bit.

We will keep the event handlers in the main file, then anything else is getting added into a sensibly named file.

Please create a new file called api.js.

Then cut this code out of main.js and paste it into api.js. Note the small change I have made of adding export in front of currentActivity and fetchNewActivity:

1const activity = document.getElementById("activity");
2const type = document.getElementById("type");
3const participants = document.getElementById("participants");
4const price = document.getElementById("price");
5const link = document.getElementById("link");
6const linkContainer = document.getElementById("link-container");
7
8export let currentActivity;
9
10export const fetchNewActivity = () => {
11  fetch("https://www.boredapi.com/api/activity/")
12    .then((res) => res.json())
13    .then((data) => {
14      activity.innerText = data.activity;
15      type.innerText = data.type;
16      participants.innerText = data.participants;
17      price.innerText = data.price;
18
19      if (data.link.length) {
20        link.href = data.link;
21        linkContainer.hidden = false;
22      } else {
23        linkContainer.hidden = true;
24      }
25
26      currentActivity = data;
27    })
28    .catch((error) => console.log(error));
29};

Now in main.js add this line at the very top:

1import { currentActivity, fetchNewActivity } from "./api.js";

This means we can access both of those in main.js.

Now if you refresh your page and look at the console you will see this error:

1Uncaught SyntaxError: Cannot use import statement outside a module (at main.js:1:1)

To fix this we need to jump to our HTML and modify our script tag to this:

1<script src="main.js" type="module"></script>

And now your app will work again.

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co