ES6类功能中的导入模块

尼尔森·奥瓦洛

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

但是现在使用aka 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
        }
    }

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

有需要时可以根据需要动态导入文件的方法吗?

尼尔森·奥瓦洛

通过对该答案进行一些修改,我设法通过以下方式使其起作用:

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
    });

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章