Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to export object in es6 module

I'm trying to export an my module as an object but exporting it seems an 'anti pattern' (https://medium.com/@rauschma/note-that-default-exporting-objects-is-usually-an-anti-pattern-if-you-want-to-export-the-cf674423ac38)

So I was wondering what's the correct way to export an object and then use it as

import utils from "./utils" `

utils.foo()

Currently I'm doing like so

    /** a.js **/
    function foo(){
      //...
    }

    export {
      foo
    }

    /** b.js **/
    import * as utils from "a";

    utils.foo()

is it correct like so? Do I maintain the tree-shaking feature?

thanks

like image 375
kiwi1342 Avatar asked Sep 11 '25 05:09

kiwi1342


1 Answers

If the object you want to import/export only contains some functions (as I assume due to the Utils name), you can export the functions separately as follows:

export function doStuff1() {}
export function doStuff2() {}

And import like this:

import {doStuff1, doStuff2} from "./myModule";

However, if the object you want to export holds state in addition to methods, you should stick to a simple export default myObject. Otherwise, calling the imported methods won't work as intended, since the context of the object is lost.

As an example, the following object should be exported as a whole, since the properties of the object should stay encapsulated. Only importing and calling the increment function would not mutate myObject since the context of the object cannot be provided (since it's not imported as a whole).

const myObject = {
    counter: 0,
    increment: function() {
        this.counter++;
    }
}
export default myObject;
like image 89
Philipp Avatar answered Sep 13 '25 18:09

Philipp