Idiomatic Detection Module for ES6

In the past, I used a module expansion template .

function myModule() { function foo() ... function bar() ... return { foo: foo, bar: bar }; } 

With ES6, this has improved with object reduction.

 function myModule() { function foo() ... function bar() ... return { foo, bar }; } 

Now, using the built-in module syntax, I am struggling to find a preferred template that is most similar to the one above.

Option number 1 with the name export

 // export file function foo() ... function bar() ... export { foo, bar }; // import file import { foo, bar } from './export-file'; foo(); bar(); 

Default option # 2 export / import with destructuring

 // export file function foo() ... function bar() ... export default { foo, bar }; // import file import baz from './export-file'; const { foo, bar } = baz; foo(); bar(); 

Option No. 3 by default export / import with an interval between names

 // export file function foo() ... function bar() ... export default { foo, bar }; //import file import baz from './export-file'; baz.foo(); baz.bar(); 

I like Option # 1 with the specified export for the simplicity it offers in the "destructuring" import syntax.

 import { foo, bar } from './export-file'; 

I also want to continue working with the exported API module explicitly indicated at the bottom of the exporting file in the export object.

 export { foo, bar }; // OR export default { foo, bar }; 

I read all the time that default preferences are preferable, so I tried to find a preferred template that includes default exports, but I am reluctant to accept, because it just seems more detailed with a slight advantage (except for the need for line spacing or the inclusion of both named and export by default in some cases).

Is there an idiomatic pattern for identifying a module template with ES6 module syntax?

+8
javascript es6-modules
source share
1 answer

I read all the time that default exports are preferred

No, it is not. They are simpler and have shorter syntax and can be used more often (since there are smaller modules with one export), but usually they are not preferred.

Use the right tool for the job. You already know the benefits you want.

Is there an idiomatic pattern for identifying a module template with ES6 module syntax?

Yes, Option No. 1. When you have a few things to export, always use named exports.

You get both explicit smoothing and tree formation from the syntax

 import { foo, bar } from './export-file'; 

as well as namespaces

 import * as baz from './export-file'; 
+6
source share

All Articles