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



我正在开发VUEJS,Typescript和WebPack中的Web应用程序,我对如何管理/拆分函数组(实用程序和服务)有些困惑。

我在github的各个项目中看到了某些功能被声明并直接从文件中导出:

Utilities.ts

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

这可以与导入一起使用:

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

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

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 const OtherUtilities = {
    Sum(a:number, b:number) : number => {
        return a+b;
    },
    Hello() : string => {
        return "Hello";
    }
}

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

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

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

它们是可以摇晃的。如果您的申请仅发生到导入Hello(),则可以从捆绑包中删除Sum

现在,使用第二种策略,您更有可能命名碰撞。您可以使用as关键字来防止它们:

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

除了树木颤抖之外,我认为一种样式或另一种样式之间没有太大差异。您可以用eCmascript模块导出任何内容,是否是函数,字符串,数字或任何其他类型的原语,数组或对象。这取决于您和团队的代码约定。

一些用于导出属于大实用对象的独立功能的库,但随后更改了样式并切换到独立的命名出口,精确地使树木摇动(有时,只有独立的项目就这样做,例如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;
    }
}

最新更新