Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...