【问题标题】:import and call a function with es6 [duplicate]使用es6导入和调用函数[重复]
【发布时间】:2015-10-14 11:29:54
【问题描述】:

以前:

var debug = require('debug')('http')
  , http = require('http')
  , name = 'My App';

使用 es6,如何像第一行一样立即导入和调用?

import debug from 'debug'();

不可以吗?

【问题讨论】:

    标签: javascript ecmascript-6 babeljs


    【解决方案1】:
    import http from "debug"; // not sure if this is the desired effect
    

    【讨论】:

    • 请放心,这并没有预期的效果
    【解决方案2】:

    你需要两行:

    import debugModule from 'debug';
    const debug = debugModule('http');
    

    导入语法是一种声明式导入语法,它不执行任何函数。

    【讨论】:

    • 问题是有时您需要在任何其他导入语句之前调用该函数。 import 不允许在声明所有 import 语句之前执行其他语句。
    【解决方案3】:

    不可以吗?

    正确。请记住,import 语句不仅类似于简单的require() 语句——它还创建了“已加载”模块与局部变量的绑定。

    也就是说,

    import debug from 'debug'();
    

    ...在行为/语义上更接近于

    var debug = require('debug');
    

    ...比简单的

    require('debug');
    

    commonjs 样式的模块加载器的类比显然会在某些时候崩溃,但归根结底这是一个“不不”,因为import debug from 'debug' 实际上并没有解决任何问题您可以调用(或以其他方式引用)。

    【讨论】:

      猜你喜欢
      • 2016-11-22
      • 1970-01-01
      • 2017-02-23
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      • 2016-10-11
      相关资源
      最近更新 更多