62

In version 5.6.4 of BabelJS, I seemingly cannot "import ... as." Here are examples of what I am trying to do:

In file 'test.js':

export default class Test {};

In file 'test2.js' (in the same directory):

import Test as Test2 from './test';

I have also tried to do:

import {Test as Test2} from './test';

Even though it says nothing about that here: http://babeljs.io/docs/learn-es2015/#modules

And only uses brackets in the non-default syntax here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Has anyone done this successfully?

EDIT: It is absolutely because of the default keyword. So, in this case, the question becomes, does anyone have any links to documentation that states that I should not be able to alias a default import? ECMA or Babel.

Cœur
  • 32,421
  • 21
  • 173
  • 232
BTC
  • 3,152
  • 4
  • 23
  • 38
  • related: [How can I alias a default import in Javascript?](https://stackoverflow.com/q/39282253/1048572) – Bergi Oct 17 '19 at 22:06

1 Answers1

143

You can import the default export by either

import Test2 from './test';

or

import {default as Test2} from './test';

The default export doesn't have Test as a name that you would need to alias - you just need to import the default under the name that you want.

The best docs I've found so far is the article ECMAScript 6 modules: the final syntax in Axel Rauschmayers blog.

Bergi
  • 513,640
  • 108
  • 821
  • 1,164
  • 2
    Ah default...let me try that. – BTC Jun 27 '15 at 18:48
  • That works excellently! Thank you. Dr. Rauschmayers blog, btw, I consider a reliable enough source to be the spec. – BTC Jun 27 '15 at 18:51
  • Well you can check out [the spec](http://www.ecma-international.org/ecma-262/6.0/#sec-modules) as well, but I think that blog is more readable :-) – Bergi Jun 27 '15 at 18:52
  • 1
    From MDN, it looks like you could also do `import * as Test2`. – Merlin -they-them- Aug 04 '17 at 10:11
  • @merlinpatt You have to use `Test2.default` then, though - it's a module namespace object. – Bergi Aug 04 '17 at 12:50
  • @Bergi thank you for the pointing that out. It wasn't clear from the docs. What is the point of allowing that? – Merlin -they-them- Aug 04 '17 at 13:47
  • @merlinpatt So that you don't have to declare all names that you want to use. E.g. `import { * as _ } from 'underscore'` will get you the `_` namespace, instead of having to write out all function names. – Bergi Aug 04 '17 at 14:00