Javascript 导入类并使用带有 babel 转译器的 es6 模块调用静态方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28974784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:40:54  来源:igfitidea点击:

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

javascriptecmascript-6

提问by dagda1

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']

我不确定默认值是什么 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

回答by alexpods

You have two options:

您有两个选择:

  1. Export EmberRefluxlike you are doing:

    export { EmberReflux };
    

    and then import it like:

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

    export default EmberReflux;
    

    and import it (like you are doing):

     import EmberReflux from '../utils/ember-reflux';
    
  1. EmberReflux像您一样导出:

    export { EmberReflux };
    

    然后像这样导入:

    import { EmberReflux } from '../utils/ember-reflux';
    
  2. default导出时使用:

    export default EmberReflux;
    

    并导入它(就像你在做的那样):

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

In both cases you can then use your EmberRefluxlike:

在这两种情况下,您都可以使用您EmberReflux喜欢的:

EmberReflux.createActions();

回答by Victor Castro

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

我没有足够的声誉来发表评论,alexpods 的回答是完美的,但对于理解我们的朋友 Ced 的问题:

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

为什么我们需要第二个例子中的默认值?换句话说,为什么我们不能直接导出 EmberReflux ?

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:

这就是为什么你需要运行 EmberReflux.EmberReflux,解决方法很简单:

export default EmberReflux;