Codiqo

Learn JavaScript · lesson 39 of 60 · about 8 minutes

import and export

Make links for Sam's posts: share code between files with modules, and understand where npm packages fit in.

What you'll learn

  • Export functions and values
  • Import named and default exports
  • Explain what npm packages are

Links for the posts

Each post needs its own link, like /posts/hello-world. slug(title) turns a title into the last part: lower case, with every run of characters that aren't letters or digits (/[^a-z0-9]+/g) replaced by a dash, and any dash at either end removed. postLink(post) puts /posts/ in front. Sam's page is getting long, and these helpers will soon be used by a second page too, so they're marked with export: any other file can then bring them in with import { slug, postLink } from "./page.js";.

Splitting code into files

Real projects are split into modules: one file per job. A file chooses what to share with export, and other files bring it in with import.

In a file called maths.js:
- export function add(a, b) { ... } is a named export
- export default function main() { ... } is the file's default export

In another file:
- import { add } from "./maths.js"; takes the named export
- import main from "./maths.js"; takes the default export

A module exports what it shares (one file shown)

export const PI_ISH = 3.14;

export function circleArea(r) {
  return PI_ISH * r * r;
}

console.log(circleArea(10));

Output

314

Built-in modules and npm

Node comes with built-in modules you import with a node: prefix. npm is a huge online library of packages written by others: npm install dayjs downloads one, then you import dayjs from "dayjs".

Importing a built-in module

import { basename, extname } from "node:path";

const file = "/projects/codiqo/notes.txt";
console.log(basename(file));
console.log(extname(file));

Output

notes.txt
.txt

Tip

Imports go at the top of a file. Anyone reading it can see straight away what it depends on.

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.