首页 > 解决方案 > 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
    }
}

但是现在当使用 Michael Jackson Scripts aka 时.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
        }
    }

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

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

标签: node.jsecmascript-6es6-modules

解决方案


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

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

这适合我现在,直到规范最终确定并发货


推荐阅读