最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Correct way to export object in es6 module - Stack Overflow

programmeradmin2浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论