Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import class and call static method with es6 modules with babel transpiler

I have the following class definition:

class EmberReflux{
  static createActions(actions) {
    console.log(actions);
  }
}

export { EmberReflux };

When I import it from a different file:

import EmberReflux from '../utils/ember-reflux';

let TodoActions = EmberReflux.createActions(
[
  "addItem",
  "undo",
  "redo"
]);

export { TodoActions };

The transpiled looks like this

define('ember-reflux/utils/todo-actions', ['exports', 'ember-reflux/utils/ember-reflux'], function (exports, EmberReflux) {

    'use strict';

    var TodoActions = EmberReflux['default'].createActions(["addItem", "undo", "redo"]);

    exports.TodoActions = TodoActions;

});

I'm not sure what the default is in EmberReflux['default']

I want to call the static class method like this:

EmberReflux.createActions

But instead I have to call it like this:

EmberReflux.EmberReflux.createActions
like image 846
dagda1 Avatar asked Mar 10 '15 21:03

dagda1


2 Answers

You have two options:

  1. Export EmberReflux like you are doing:

    export { EmberReflux };
    

    and then import it like:

    import { EmberReflux } from '../utils/ember-reflux';
    
  2. Use default when exporting:

    export default EmberReflux;
    

    and import it (like you are doing):

     import EmberReflux from '../utils/ember-reflux';
    

In both cases you can then use your EmberReflux like:

EmberReflux.createActions();
like image 197
alexpods Avatar answered Oct 23 '22 18:10

alexpods


I don't have enough reputation to comment, the alexpods's answer is perfect, but for matters of understanding our friend Ced asked:

Why do we need the default in the 2nd example ? In other words why can't we have export EmberReflux directly ?

When you wrote like this:

export { EmberReflux };

It's the same writing like this:

export { EmberReflux: EmberReflux };

That's why you need to run EmberReflux.EmberReflux, the solution is very simple:

export default EmberReflux;
like image 22
Victor Castro Avatar answered Oct 23 '22 18:10

Victor Castro