Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Are * and default the same?


No. The former imports all the exports, and the latter imports the default export only.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...


`*` is the namespace object. `default` is a special named property on the namespace object.

someModule.js:

    export default 'foo';
    export const bar = 'bar';
namespaceImport.js:

    import * as SomeNamespace from './someModule.js';
    console.assert(SomeNamespace.default === 'foo');
    console.assert(SomeNamespace.bar === 'bar');
defaultImport.js:

    import foo from './someModule.js';
    console.assert(foo === 'foo');
namedImports.js:

    import { default as foo, bar } from './someModule.js';
    console.assert(foo === 'foo');
    console.assert(bar === 'bar');


Note that there's an error on the default export:

    - export default foo = 'foo';
    + export default 'foo';


thanks, fixed


A lot of 'x1' should be 'x2' in the examples


Can you clarify the question? In what sense are you asking if they're the same / not the same?

In general, `import * from X` will pull every exported symbol of X into your current module at the top level (generally not recommended except for special cases like testing libraries; you shackle yourself to an assumption that the imported module won't ever add new symbols that might interact surprisingly with the importing module). `import * as Y from X` is slightly safer; it'll pull in all the exported symbols from X, but will wrap them in a Y namespace (so X's `foo` function is now `Y.foo`, etc.). `import {foo} from X` will just import the `foo` symbol from X and make it available in your module. Finally, `import foo from X` imports the single export in X that is tagged as default and names it `foo` in your module.

(To my money, I don't like defaults very much. I much prefer `import {foo} from X` over `import foo from X` for clarity, even if `foo` is the only symbol X exports. It allows for future growth of X and avoids the unsightly `import foo, {bar} from X` that some modules end up growing in the future).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: