Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6+ javascript module export options

I've seen public exports of ES6 modules done in both of the following ways:

// method 1 export var getAnswer = function () { return 'forty two'; };  // method 2 export default function () { return 'forty two'; }; 
  1. Are both of these valid?
  2. If so, why do they both exist?
  3. Are there other valid options for module exports using ES6 syntax?

I'm surprised I haven't been able to find the answer with my googlefu. I'm concerned only with ES6 modules, not CommonJS, RequireJS, AMD, Node, etc.

like image 825
kdbanman Avatar asked Aug 25 '14 21:08

kdbanman


People also ask

What are the two types of module exports in JavaScript?

Every module can have two different types of export, named export and default export.

Is module exports ES6?

All CommonJS and AMD modules are presented to ES6 as having a default export, which is the same thing that you would get if you asked require() for that module—that is, the exports object. ES6 modules were designed to let you export multiple things, but for existing CommonJS modules, the default export is all you get.

How many exports can a module have?

A module can have one and only one default export.

How many default exports can a ES6 JS file have?

One can have only one default export per file.


1 Answers

A year and some later, here is the best information I've found on the subject.

There are 4 types of exports. Here are usage examples of each, along with some imports that use them:

Export Syntax

// default exports export default 42; export default {}; export default []; export default (1 + 2); export default foo; export default function () {} export default class {} export default function foo () {} export default class foo {}  // variables exports export var foo = 1; export var foo = function () {}; export var bar; export let foo = 2; export let bar; export const foo = 3; export function foo () {} export class foo {}  // named exports export {}; export {foo}; export {foo, bar}; export {foo as bar}; export {foo as default}; export {foo as default, bar};  // exports from export * from "foo"; export {} from "foo"; export {foo} from "foo"; export {foo, bar} from "foo"; export {foo as bar} from "foo"; export {foo as default} from "foo"; export {foo as default, bar} from "foo"; export {default} from "foo"; export {default as foo} from "foo"; 

Import Syntax

// default imports import foo from "foo"; import {default as foo} from "foo";  // named imports import {} from "foo"; import {bar} from "foo"; import {bar, baz} from "foo"; import {bar as baz} from "foo"; import {bar as baz, xyz} from "foo";  // glob imports import * as foo from "foo";  // mixing imports import foo, {baz as xyz} from "foo"; import foo, * as bar from "foo";  // just import import "foo"; 

Source.

like image 131
kdbanman Avatar answered Oct 21 '22 16:10

kdbanman