kiwi1342
kiwi1342

Reputation: 1389

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

Upvotes: 4

Views: 11959

Answers (2)

Philipp
Philipp

Reputation: 731

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;

Upvotes: 5

Sergio Belevskij
Sergio Belevskij

Reputation: 2947

es6 native way to do this:

// file1.es6
export const myFunc = (param) => {
  doStuff(param)
}

export const otherFunc = ({ param = {} }) => {
  doSomething({ ...param })
}

// file2.es6
import { otherFunc } from './file1.es6'
import * as MyLib from './file1.es6'

MyLib.myfunc(0)
MyLib.otherFunc({ who: 'Repley' })
otherFunc({ var1: { a1: 1 } })

And so on.

Upvotes: -1

Related Questions