简体   繁体   中英

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

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();

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;
class EmberReflux {
    //...
}

module.exports = EmberReflux

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM