Basic Exporting

You can use the export keyword to expose parts of published code to other modules. In the simplest case, you can place export in front of any variable, function, or class declaration to export it from the module, like this:

  1. // export data
  2. export var color = "red";
  3. export let name = "Nicholas";
  4. export const magicNumber = 7;
  5. // export function
  6. export function sum(num1, num2) {
  7. return num1 + num1;
  8. }
  9. // export class
  10. export class Rectangle {
  11. constructor(length, width) {
  12. this.length = length;
  13. this.width = width;
  14. }
  15. }
  16. // this function is private to the module
  17. function subtract(num1, num2) {
  18. return num1 - num2;
  19. }
  20. // define a function...
  21. function multiply(num1, num2) {
  22. return num1 * num2;
  23. }
  24. // ...and then export it later
  25. export { multiply };

There are a few things to notice in this example. First, apart from the export keyword, every declaration is exactly the same as it would be otherwise. Each exported function or class also has a name; that’s because exported function and class declarations require a name. You can’t export anonymous functions or classes using this syntax unless you use the default keyword (discussed in detail in the “Default Values in Modules” section).

Next, consider the multiply() function, which isn’t exported when it’s defined. That works because you need not always export a declaration: you can also export references. Finally, notice that this example doesn’t export the subtract() function. That function won’t be accessible from outside this module because any variables, functions, or classes that are not explicitly exported remain private to the module.