3 ms·
Are * and default the same?
by k__ 4y ago
Are * and default the same?
- deleted 4y ago[deleted]
- shadowgovt 4y agoCan 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).
- FrontAid 4y agoNo. The former imports all the exports, and the latter imports the default export only. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#namespace_import https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#default_import https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- AprilArcus 4y ago`*` 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');
- HeavyFeather 4y agoNote that there's an error on the default export: - export default foo = 'foo'; + export default 'foo';
- AprilArcus 4y agothanks, fixed
- jenadine 4y agoA lot of 'x1' should be 'x2' in the examples