Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better to export an object containing function, or just export multiple functions in ES6 (Is there a convention?)

This is a question of convention. I'm new to ES6 but I'm trying to make use of the module system. Is preferred/more common to export multiple functions from a single file, or export a single object containing these functions.

Example:

utils.js

export function add(num1, num2) {   return num1 + num2; }  export function minus(num1, num2) {   return num1 - num2; } 

and use it like this:

import {add, minus} from 'utils.js'; 

vs

utils.js

const utils = {   add: (num1, num2) => {     return num1 + num2;   },    minus: (num1, num2) => {     return num1 - num2;   } }  export default utils; 

In a utils file that contains a 50-100 functions, it seems the second way would be the clear winner. But there's just something that feels wrong about it to me, and I don't know why.

like image 842
charrondev Avatar asked Jan 11 '16 05:01

charrondev


2 Answers

Going forward, it's probably better to export multiple functions, as tree shaking allows module bundlers to eliminate dead code based on whether it's been imported or not.

If you export one large object, it's not always possible to use static analysis to tell which functions need to be kept and which can be safely discarded.

If you export multiple named functions, then the module bundler can analyze the AST then safely whitelist the functions which you are actually importing.

like image 103
Dan Prince Avatar answered Sep 20 '22 16:09

Dan Prince


If you have as you say 50-100 functions that you want to expose through your utils file then I'd say go with the named exports

export function add() {} 

Since otherwise every time an import of utils would take place you'd import the all of the functions. This might be what you want sometimes but most likely there'll only be a handful of useable functions for any given module. If you want all of the functions a simple import * as utils from './utils'; would suffice.

However there is nothing that doesn't say you can use both patterns if you want to safe guard against it.

export function add() {};  const utils = {    add: add }; export default utils;  

Above is both valid and quite common as well.

Just remember as of Babel 6.x when developing a library using the export default will actually produce an object (the correct way) containing a default property on which your exported object will be attached to.

import utils from './utils';  console.log(utils); // { default: yourUtilsObject } 
like image 40
Henrik Andersson Avatar answered Sep 20 '22 16:09

Henrik Andersson