【问题标题】:Execute a module immediately after calling import in ES6 [duplicate]在ES6中调用导入后立即执行模块[重复]
【发布时间】:2018-02-03 02:06:52
【问题描述】:

我正在做一些关于 NodeJS 的工作,我正在使用 ES6 语法中的 import 关键字。我想在调用它后立即执行。我搜索了类似的想法来做到这一点,但没有任何帮助。

我要做的基本上是将以下代码从CommonJS转换为ES6。

// In CommonJS:
var birds = require('./birds')()

// In ES6:
import birds from './birds'()

我可以使用 const 关键字来做到这一点:

import birds from './birds'
const SomethingButNotBirds = birds()

但是,我真的很想知道是否有更好的方法。

非常感谢你们的帮助!

【问题讨论】:

    标签: javascript node.js ecmascript-6


    【解决方案1】:

    ES6 import 语句具有声明性语法,不会像require()() 那样为您提供执行函数的空间。

    下面的代码是唯一有效的方法。

    import birds from './birds'
    const SomethingButNotBirds = birds()
    

    【讨论】:

    • 好的。实际上这样做很好。但这里唯一的问题是我将无法使用我想要的相同变量。你认为有比import birdsRoutes from './birds'const birds = birdsRoutes()更好的技术吗。或类似:const birds = require('./birds')()。想想看,您彼此之间有 +15 条路线。你会怎么做?
    • 您可以尝试import * as bd from './birds'; 并使用const bird = bd.bird() 但是,您应该知道这在导入 * 导入鸟类中的所有函数时存在性能问题
    • 看起来可行!我会搜索* as bd 语法,我会尽快尝试。感谢您的帮助。
    • @YahiaRefaiea 好的。如果我的回答对您有所帮助,您可以投票赞成。
    • @FortuneEkeruo 你关于性能的观点不太正确。两种形式都会加载整个文件,只是捆绑器在判断给定函数是否实际使用方面的能力有所不同。他们中的很多都太安全地支持命名空间版本。
    猜你喜欢
    • 2020-09-21
    • 1970-01-01
    • 2016-09-16
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多