Skip to content

Latest commit

 

History

History
80 lines (55 loc) · 2.94 KB

File metadata and controls

80 lines (55 loc) · 2.94 KB

export

The export keyword is used to define which elements in the current file will be importable into other files using the import keyword.

There are two types of exports, the default export and named exports.

Default export

The default export is marked using the default modifier:

export default class XYZ {}

Named exports

Named exports can have multiple forms, some of those are:

export class XYZ {}
export const foo = 'bar';
export { foo, bar }; // this exports a list of multiple features

Export-from-syntax / Re-exporting modules

There is also a syntax that allows for importing modules and directly exporting all or parts of it:

export * from 'other_module'; // exports all features of `other_module`
export { foo, bar } from 'src/other_module'; // exports foo & bar from `other_module`
export { foo as myFoo, bar } from 'src/other_module'; // renaming also works

One caveat about re-exporting is that default exports are ignored by this syntax (as explained here).

Transpilation

To make exports work, we use transpilers like babel or tsc that take those modules and convert them into own file (or even multiple). Babel also has the benefit of another form of exports, the so-called synthetic default export:

exports = class XYZ {};

Which will be translated the first mentioned example (export deafult class XYZ{}).

ECMAScript 6 modules vs CommonJS modules

There are different kind of modules that have different ways how to export things. The examples above are all ECMAScript 6 modules and are mostly available through preprocessors like babel. In Node.js environments however CommonJS modules are used. They usually take the following form (note that there is no default export):

var foo = 42;
function square(x) {
  return x * x;
}
module.exports = {
  foo: foo,
  square: square,
};

Where to use

The export keyword, just like import, can only be used in a module, which means it has to be run in Node.js, transpiled by babel or similar, or be used in a file included in the browser directly using <script type="module" src="…">.

Further reading

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

https://exploringjs.com/es6/ch_modules.html#sec_basics-of-es6-modules