DEV Community

loading...
Cover image for ES6 Modules

ES6 Modules

tiffany profile image Tiffany White Originally published at tiffanywhite.tech on ・2 min read

ES6 modules allows us to have reusable code, in separate files. We do this to eliminate initially massive js files, like app.js in a Node and Express project. Modules allow us to spread code over relevant files.

Take this students.js file

const students = [Peter, Paul, Mary];

export const students = [Peter, Paul, Mary];
Enter fullscreen mode Exit fullscreen mode

Export allows us to export functions, objects, and primitive values into another files.

In app.js we import those values as modules into the main js file:

import { students } from ./students;
Enter fullscreen mode Exit fullscreen mode

…where ./students represents the file stored in the same directory as app,js.

Importing More than One Value

You can import more than one value from a module. Take students.js:

export const total = 42;
Enter fullscreen mode Exit fullscreen mode

We can import this variable into app.js along with the students array:

import { students, total } from ./students;
Enter fullscreen mode Exit fullscreen mode

Export Data and Functions Between Files

You can export functions between files, such as in this calc.js file:

const add = (x, y) => {
  return x + y;
}

const divide = (x, y) => {
  return x / y;
}

export { add, divide };
Enter fullscreen mode Exit fullscreen mode

To import this module into app.js:

import { add, divide } from ./calc;
Enter fullscreen mode Exit fullscreen mode

Exports are not just limited to primitive data types.

Export Fallbacks with Default

What if we wanted a function to be the main function for our module?

We can add a default keyword to have a fallback:

export { add, divide };
export default multiply;
Enter fullscreen mode Exit fullscreen mode

This will allow the module to fallback on a function if another fails.

Watch for this Pitfall

It may be tempting to do something like this:

export default const add = (x, y) => {
  return x + y;
}
Enter fullscreen mode Exit fullscreen mode

This will result in a TypeError.

Why?

The default keyword creates a variable called default. Adding default and const simultaneously, JavaScript will try to declare two different variables, which is not allowed in most programming languages.

More to Come

ES6 is the standard now and so I am learning it, as quickly as possible. Let me know some of your favorite features of ES6.

The post ES6 Modules appeared first on Tiffany R. White Blog.

Discussion (0)

pic
Editor guide