Modules

Lets explore another common function pattern called modules.


Modules

  • Export functions
  • Easy imports
  • Variable protection

Modules allow you to put the functions you want to make available to one or more projects and store them in a separate file.

You can easily import just the functions you need from one javascript codebase to another.

The best part is that it lets you create variables and other functions that are local to the library codebase, so there's no chance that any variables inside your modules will polute anything you're doing in your main code.


Modules

export function squared(a) {
  return a * a;
}

export function add(a,b) {
  return a + b;
}
//lib.js

The way we write modules in JavaScript has changed for the better in the newer versions of javascript.

To create a module, all you have to do is create a file that has a function with an export keyword at the beginning.


Importing

import { squared, add } from "./lib.js";

To import this code into another javascript file, you simply use the import command.

This can bring one or more functions separated by commas from a module to your current file.


Renaming

import { squared as squareNums, add } from "./lib.js";

You can easily rename the functions you import so that they have a different name inside the file you're importing them too.

That's another way to make sure that if you're already using a function that has the name, it can be imported with a different name.


Defaults

export default function squared(a) {
  return a * a;
}

export function add(a,b) {
  return a + b;
}
//lib.js
import squareNums, { add } from './lib.js'

If you add the default keyword, then it's a bit easier when you import the function, you don't have to put it in curly braces.

You can still import other functions by putting them in curly braces.


Importing Everything

import * as lib from "./lib.js";

console.log(lib.default(3));
console.log(lib.add(3,5));

Try It

You can use the asterisk to impport all of the functions. Be careful when you're doing this because importing everything adds things that you might not need on a project, making your code larger and more efficient.