admin管理员组

文章数量:1327299

I'm trying to export an my module as an object but exporting it seems an 'anti pattern' (/@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

I'm trying to export an my module as an object but exporting it seems an 'anti pattern' (https://medium./@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

Share Improve this question edited Sep 8, 2017 at 12:39 kiwi1342 asked Sep 8, 2017 at 12:25 kiwi1342kiwi1342 1,3894 gold badges15 silver badges23 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 5

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.

本文标签: javascriptCorrect way to export object in es6 moduleStack Overflow