简体   繁体   中英

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

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM