export Keyword

Examples

Using named exports

In a module my-module.js, we could include the following code:

// module "my-module.js"
function cube(x) {
  return x * x * x;
}

const foo = Math.PI + Math.SQRT2;

const graph = {
  options: {
    color: 'white',
    thickness: '2px',
  },
  draw() {
    console.log('From graph draw function');
  }
};

export { cube, foo, graph };

Then in the top-level module included in your HTML page, we could have:

import { cube, foo, graph } from './my-module.js';

graph.options = {
  color: 'blue',
  thickness: '3px',
};

graph.draw();
console.log(cube(3)); // 27
console.log(foo);    // 4.555806215962888

It is important to note the following:

  • You need to include this script in your HTML with a <script> element of type="module", so that it gets recognized as a module and dealt with appropriately.
  • You can't run JS modules via a file:// URL - you'll get CORS errors. You need to run it via an HTTP server.

Using the default export

If we want to export a single value or to have a fallback value for your module, you could use a default export:

// module "my-module.js"

export default function cube(x) {
  return x * x * x;
}

Then, in another script, it is straightforward to import the default export:

import cube from './my-module.js';
console.log(cube(3)); // 27


Using export from

Let's take an example where we have the following hierarchy:

  • childModule1.js: exporting myFunction and myVariable
  • childModule2.js: exporting MyClass
  • parentModule.js: acting as an aggregator (and doing nothing else)
  • top level module: consuming the exports of parentModule.js

This is what it would look like using code snippets:

// In childModule1.js
function myFunction() {
  console.log("Hello!");
}
const myVariable = 1;
export { myFunction, myVariable };
// In childModule2.js
class MyClass {
  constructor(x) {
    this.x = x;
  }
}

export { MyClass };
// In parentModule.js
// Only aggregating the exports from childModule1 and childModule2
// to re-export them
export { myFunction, myVariable } from 'childModule1.js';
export { MyClass } from 'childModule2.js';
// In top-level module
// We can consume the exports from a single module since parentModule
// "collected"/"bundled" them in a single source
import { myFunction, myVariable, MyClass } from 'parentModule.js'