14

I have the following imports:

import { default as service } from "../service";

VS

import * as service from "../service";

My service is exported like so

module.exports = {

    init(store) {
         _store = store;
    },

    beginPayment() {
    }

};

I would expect that only the second import would work since there is no export default, however both seem to work.

What is the difference between these? Is one preferred over the other?

If this is a duplicate I apologize, I didn't find anything specific to my example on SO or Google.

Brandon McAlees
  • 715
  • 2
  • 12
  • 28
  • Possible duplicate of [When should I use curly braces for ES6 import?](https://stackoverflow.com/questions/36795819/when-should-i-use-curly-braces-for-es6-import) – Pete Nov 20 '18 at 16:16
  • I didn't see the import of: { default as 'xxx' } explained in that question. Still unsure of exactly what the differences are here. – Brandon McAlees Nov 20 '18 at 16:21
  • It's the bottom one in the accepted answer, starts with *We can also assign them all different names when importing:* – Pete Nov 21 '18 at 10:03

1 Answers1

14

If you are importing the default, there has to be a default.

In general, the community appears wary of default exports at the moment as they seem to be less discoverable (I have no specific citation, but I've watched the conversation!)

If you are working in a team, whatever they say is the correct answer, of course!

So without a default, you need to use:

import * as service from "../service";

Or choose a specific thing:

import { specificNamedThing } from "../service";
Fenton
  • 241,084
  • 71
  • 387
  • 401
  • So if there is no default export, is 'import default' treated as 'import *'? In my example above I have no default export, but my first import statement works, and it seems to act like an 'import *'. – Brandon McAlees Nov 20 '18 at 16:11
  • As far as I'm aware, it is invalid to use import default if there is no export default. It _should_ throw an exception. – Fenton Nov 20 '18 at 16:13
  • 1
    @Fenton it doesn't throw an exception for me, just returns undefined. – George Nov 20 '18 at 16:14
  • I think I found out why it works for me. We use Babel to transpile our code and when turning source maps off in the chrome debugger, all our import statements are converted to Webpack requires. Makes sense why I wasn't able to find anything online. Thanks for the help! – Brandon McAlees Nov 20 '18 at 16:54