Javascript/Typescript: what's the difference between exporting single functions or a const class?

12,777

This object:

export const OtherUtilities = {
    Sum(a:number, b:number) : number => {
        return a+b;
    },

    Hello() : string => {
        return "Hello";
    }
}

Contains two completely unrelated functions. They don't need to share a this context, don't know each other, and could perfectly be exported as two separated functions, even in two separate modules. They can belong to the same object, but there is no strong reason to do that.

On the other hand, if you export them as separate entities:

export function sum()...
export function hello()...

They are tree shakeable. If your application happens to only import Hello(), them Sum can be dropped from the bundle.

Now, with the second strategy, you're more likely to get naming collisions. You can prevent them using the as keyword:

 import {Sum} from 'one';
 import {Sum as myCustomSum} from 'two';

Apart from the tree shaking, I don't think there's much differences between one style or the other. You can export anything with ECMAScript modules, would it be functions, strings, numbers or any other kind of primitives, arrays or objects. It's pretty much up to you and the code conventions of your team.

Some libraries used to export independent functions belonging to a big utility object, but then changed the style and switched to independent named exports, precisely to enable tree shaking (and sometimes, just independent projects do that, like lodash-es).

Share:
12,777

Related videos on Youtube

IGionny
Author by

IGionny

Updated on June 04, 2022

Comments

  • IGionny
    IGionny almost 2 years

    I'm developing a web application in VueJs, Typescript and WebPack and I'm a bit confused about how to manage/split groups of functions (utilities and services).

    I saw in various project in GitHub that some functions are declared and exported directly from the file ex:

    utilities.ts

    export function Sum(a:number, b:number):number{
        return a+b;
    }
    

    this can be used with an import:

    import {Sum} from "./utilities.ts"
    
    let result = Sum(5,6);
    

    Another common solution is to declare a const class:

    otherUtilities.ts
    
    export const OtherUtilities = {
        Sum(a:number, b:number) : number => {
            return a+b;
        },
        
        Hello() : string => {
            return "Hello";
        }
    }
    

    and import as:

    import {OtherUtilities} from "./otherUtilities.ts"
    
    let result = OtherUtilities.Sum(5,6);
    

    What are the differences?

    In the past, there was the Name Conflict issue with JS but now with the export/import technique via Loaders, this issue should be outdated, right?

    Thank you

  • Bergi
    Bergi about 5 years
    …and if you want to use OtherUtilities.Sum() in the code, you can still do import * as OtherUtilities from '…';.