ES6类功能中的导入模块

时间:2018-08-01 14:10:43

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

我已将项目迁移到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又名.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
        }
    }

我的应用程序中有许多文件/模块不会立即消耗,将来可以添加更多文件/模块,因此在文件开始时对导入进行硬编码是不可能的。

是否有必要在需要时动态导入文件?

1 个答案:

答案 0 :(得分:0)

通过对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
        }
    }

或者您可以使用诺言:

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

这适合我,直到最终确定并交付规格为止

相关问题