Bootcamp
Search…
📅
Course Schedule
0: Language and Tooling Teaching Guide
1: Frontend Basics Teaching Guide
2: Backend Basics Teaching Guide
3: Backend Applications Teaching Guide
4: Backend Structure Teaching Guide
5: Full-Stack Applications Teaching Guide
6: Frontend Infrastructure Teaching Guide
7: React Teaching Guide
8: Advanced React Teaching Guide
9: Advanced Topics Teaching Guide
🧮
Algorithms Teaching Guide
💼
Interview Prep Teaching Guide
☺
User Experience Teaching Guide
2.3: Modules

Module Definition

  1. 1.
    Modules define code that can be logically grouped together and imported from other files.
  2. 2.
    Modules are helpful for code decomposition where groups of helper functions can be put together in a module to abstract complexity from our main business logic.
  3. 3.
    Modules are also helpful for independent development and testing of features that we may not want to intermingle with other app logic yet.

Basic Examples

For example, we can create an addition module with an add function that we import and use in index.js.
Either named ES6 arrow functions or ES5 function syntax can be used for exports. https://stackoverflow.com/questions/39582318/export-const-arrow-function-or-basic-function​
addition.js
1
export function add(a, b) {
2
return a + b;
3
}
Copied!
index.js
1
import { add } from './addition.js';
2
​
3
console.log(add(2, 2));
Copied!
Here's an example of an imperialConversion module that we import and use in index.js.
imperialConversion.js
1
export function kilometersToMiles(kilometers) {
2
// ...
3
}
4
​
5
export function celciusToFahrenheit(temperatureCelcius) {
6
// ...
7
}
8
​
9
export function kilogramsToPounds(kilograms) {
10
// ...
11
}
Copied!
index.js
1
import {
2
kilometersToMiles,
3
celciusToFahrenheit,
4
kilgramsToPounds,
5
} from './imperialConversion.js';
6
​
7
console.log(kilometersToMiles(3));
8
console.log(celciusToFahrenheit(3));
9
console.log(kilogramsToPounds(3));
Copied!

Module Scope

Unlike imports with <script> tags in HTML, each module can only access variables that are explicitly imported or defined in itself. For example, the variable PI in the following area module is not accessible in index.js because PI is not explicitly imported or defined in index.js.
area.js
1
const PI = 3.14;
2
export function circleArea(r) {
3
return PI * (r * r);
4
}
Copied!
index.js
1
import { circleArea } from './area.js';
2
​
3
console.log(circleArea(2)); // PI is being used *inside* this function
4
console.log(PI); // You will get an error. The variable is not accessible.
Copied!

Named vs Default Exports

There are 2 ways of exporting variables from a module: named and default.

Named Exports

Named exports export specific, named variables from a given module. Modules can export 0 or more named exports.

Export selected variables from a module

Not everything in a module needs to be exported. Using named exports, we can use the export statement to explicitly export 1 or more variables. For example, in the tripCost module, calculateTax is a helper function used internally, and calculateBill is an exported function.
tripCost.js
1
const GST = 0.8;
2
​
3
function calculateTax(subTotal) {
4
return subTotal * GST;
5
}
6
​
7
export function calculateBill(items) {
8
let total = 0;
9
​
10
for (let i = 0; i < items.length; i += 1) {
11
total += items[i];
12
}
13
total += calculateTax(total);
14
​
15
return total;
16
}
Copied!

Default Exports

Omit curly braces for default imports. Each module can only have 1 default export, and default exports do not need to be imported with any specific name. Default exports are typically used when a module only needs to export 1 function. In other situations we prefer named exports for clarity of what is exported and imported.
1
export default function add(a, b) {
2
return a + b;
3
}
Copied!
1
// For default exports, the imported variable's name does not need to
2
// match the exported variable's name in the source module.
3
// For example, we could replace the following "add" with "foo".
4
import add from './maths.js';
Copied!

Less Common Patterns

Export Values

Typically we export functions, and not values, unless they are constant values used across an application.
1
export const fruits = ['banana', 'payaya'];
Copied!

Import All (*)

If there are a lot of named exports to import, sometimes we can use * to import all named exports from a given module. This is not recommended because it reduces clarity on what we are importing and what specific imported variables we plan to use.
maths.js
1
export function add(a, b) {
2
return a + b;
3
}
4
​
5
export function subtract(a, b) {
6
return a - b;
7
}
Copied!
index.js
1
import * as maths from './maths.js';
2
​
3
console.log(maths.add(2, 3)); // prints 5
Copied!
There is another common multi-file syntax in Node.js, require. For RA's default Node.js setup we will only use import. The way Node.js is set up, we must choose either require or import. In order to use import with Node.js this key-value pair must be added to package.json: "type": "module". This key-value pair has been added to all Coding Bootcamp starter repos.

Exercise

  1. 1.
    Extract the CSS colour conversion function into its own module.
  2. 2.
    Run the examples above by adding the modules above.

Further Reading

Past students have found this video helpful in introducing ES6 Modules.
Javascript Modules in 100 Seconds video here​
Last modified 2mo ago