【问题标题】:Import Module in ES6 Class FunctionES6 类函数中的导入模块
【发布时间】:2018-08-01 14:10:43
【问题描述】:

我已将我的项目迁移到 ESM,因此我在 nodejs 中的所有文件中都使用了 .mjs。

以前在 CommonJs 中,我可能需要一个位于 ES6 类函数中间的文件,以便在需要时加载它。

 module.exports = class Core{
    constructor() {
        this.init = this._init.bind(this)

        return this.init()
    }

    async _init(){
        const module = require('module')

        //use required file/module here
    }
}

但是现在当使用 Michael Jackson Scripts a.k.a .mjs 时,我无法按需导入文件:

     import Koa from 'koa'

     export default = class Core{
        constructor() {
            this.init = this._init.bind(this)

            return this.init()
        }

        async _init(){
            import module from 'module'

            //use imported file/module here
        }
    }

我的应用程序有许多文件/模块不会立即使用,并且将来可以随时添加更多,因此在文件开头对导入进行硬编码不是一种选择。

有没有办法在需要时按需动态导入文件?

【问题讨论】:

  • Dynamic import 仍然只是一个提议。我不知道目前有哪些浏览器支持它。
  • 如果您的环境仍然支持,您仍然可以使用require,否则使用动态import
  • @Bergi 不能使用 require,我正在运行带有 --experimental-modules 标志的 nodejs

标签: node.js ecmascript-6 es6-modules


【解决方案1】:

通过对this 答案的一些修改,我设法让它通过:

import Koa from 'koa'

     export default = class Core{
        constructor() {
            this.init = this._init.bind(this)

            return this.init()
        }

        async _init(){
            const router = await import('./Router')

            //use imported file/module here
        }
    }

或者,如果您对此感兴趣,可以使用 Promise:

   import('./router')
    .then(something => {
       //use imported module here
    });

在规范最终确定并发货之前,这适合我

【讨论】:

    猜你喜欢
    • 2018-09-28
    • 2019-01-10
    • 2017-01-04
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    相关资源
    最近更新 更多