揭示模块模式结合 ES6 模块

Revealing module pattern combined with ES6 modules

我不知道哪种方法更适合 ES6 模块和显示模块模式。来自 ES6 模块的数据/功能是否像 IIFE 一样私有?

我应该只使用 *only ES6 模块吗,像这样:

// Export file

export const test = () => {
 console.log('Hello from test');
}

// Import file

import { test } from "./test.js";

test();

或者我应该两者结合使用:

// Export file

export const revealingPattern = (function() {
    function test() {
        console.log('Hello from test');
    }

    return {
        test
    }
})();

// Import file

import { revealingPattern } from "./test.js";
revealingPattern.test();

暴露模块模式的主要目的是保持数据封装,但 ES6 模块的顶层已经私有 - 其中定义的变量不会泄漏到全局范围(除非您显式分配给全局对象,如 window.foo = 'foo')。

因此,在 ES6 模块中,揭示模块模式实际上没有任何意义 - 随意在顶层定义您想要的任何内容,它的作用域将限定在模块(并且仅限于模块) , 然后你可以显式 export 任何需要透露的内容(并且不会意外地透露任何其他内容)。