Javascript/Typescript:导出单个函数或 const class 有什么区别?

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

我正在使用 VueJs、Typescript 和 WebPack 开发 Web 应用程序,我对如何 manage/split 函数组(实用程序和服务)感到有点困惑。

我在 GitHub 的各种项目中看到一些函数是直接从文件 ex:

声明和导出的

utilities.ts

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

这可以与导入一起使用:

import {Sum} from "./utilities.ts"

let result = Sum(5,6);

另一个常见的解决方案是声明一个 const class:

otherUtilities.ts

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

并导入为:

import {OtherUtilities} from "./otherUtilities.ts"

let result = OtherUtilities.Sum(5,6);

有什么区别?

以前 JS 有名称冲突问题,现在 export/import 通过 Loaders 技术,这个问题应该已经过时了吧?

谢谢

这个对象:

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

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

包含两个完全不相关的函数。它们不需要共享 this 上下文,彼此不认识,并且可以完美地导出为两个单独的函数,即使在两个单独的模块中也是如此。它们可以属于同一个对象,但没有充分的理由这样做。

另一方面,如果将它们导出为单独的实体:

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

他们是tree shakeable。如果您的应用程序碰巧只导入 Hello(),它们 Sum 可以从包中删除。

现在,使用第二种策略,您更有可能发生命名冲突。您可以使用 as 关键字阻止它们:

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

除了 tree shaking,我认为一种风格或另一种风格之间没有太大区别。您可以使用 ECMAScript 模块导出任何内容,可以是函数、字符串、数字或任何其他类型的基元、数组或对象。这在很大程度上取决于您和您团队的代码约定。

一些库过去常常导出属于大型实用程序对象的独立函数,但后来改变了样式并切换为独立的命名导出,正是为了启用 tree shaking(有时,只有独立项目才会这样做,比如 lodash-es).

使用函数:

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

使用方法:

export class Math {
    static sum(a: number, b: number): number {
        return a + b;
    }
}