Split files, borrow parts

INPUT · Slides

Pointing at where a file is

01 / 05

./ means "the folder I am in"

The ./ in the './tools.js' you have been writing has a meaning. It is the mark for "the same folder as this file".

If main.js and tools.js sit side by side, that gets there. It feels like calling someone in the same room by name.

02 / 05

Put it in a folder and the route changes

As files pile up you start wanting to gather them into folders by kind. Say you made a folder called lib and put tools.js in it.

Then the route seen from main.js becomes ./lib/tools.js. Just one folder name slipped in.

// main.jsimport { add } from './lib/tools.js';console.log(add(2, 5));

Result

7

03 / 05

../ means "one folder up"

Now the other way. Suppose from lib/tools.js you want to load rate.js, which sits right outside.

For that you write '../rate.js'. The ../ means "go up one". To go up two, stack it as '../../'.

// lib/tools.jsimport rate from '../rate.js';export function showRate() {  console.log(`${rate}%`);}

04 / 05

The base is "the file that line is written in"

This is the easiest thing to get wrong. The base for a relative path is not the main.js that started running, but the place of the file the import itself is written in.

Pointing at the same rate.js, the route changes with where you write it.

  • from main.js, './rate.js'
  • from lib/tools.js, '../rate.js'

When in doubt, start from "where is this file, again?".

05 / 05

Do not leave the extension out

You may see somewhere a way of writing it that drops the .js, like './lib/tools'. That is only tooling filling it in for you; as it stands it does not work.

Here, write it out: './lib/tools.js'. It saves you wondering, and it loads the same wherever you run it.

Right — let us join up across folders.