CodeBlanks Logo Icon CodeBlanks

Exporting as a module

JavaScript course · Advanced · Lesson 22/100

Export the class with both named and default exports.

Named export

To use the class in other files we must export it from the module. ES modules offer two ways. The first is a named export: export { Collection }. This requires the importing side to ask for it by the same name.

A module can have several named exports, so we can gather small pieces in one file and offer them separately. The importing side writes import { Collection }.

Default export

The second way is a default export: export default Collection. A module has only one default; the importing side can give it any name and writes it without curly braces.

We can use named and default exports together in the same file. This flexibility lets libraries be used both by name and by a short name. We'll add both.

Exercise Export the class as named and default

Export the class as a module: add both a named export (export { Collection }) and a default export (export default Collection).

Show example solution
For the named export write export { Collection }. For the default write export default Collection.

Example solution:
// Utility library
class Collection {
  constructor() {
    this.items = [];
  }
  add(item) {
    this.items.push(item);
    return this;
  }
  remove(item) {
    const index = this.items.indexOf(item);
    if (index !== -1) {
      this.items.splice(index, 1);
    }
    return this;
  }
  find(callback) {
    for (const item of this.items) {
      if (callback(item)) {
        return item;
      }
    }
    return undefined;
  }
}

export { Collection };
export default Collection;

Test yourself

  1. What does export default Collection provide?

    • It hides the class
    • It makes the class static
    • It gives the class a named export
    • It gives the module a default export
    Show answer

    It gives the module a default export — Correct! export default sets the module's default unit.

  2. Write the named export

    export ____;
    Show answer
    export { Collection };
  3. Match exports and imports

    export { X }
    named export
    export default X
    default export
    import X
    default import
    import { X }
    named import

All lessons in Advanced