Nelson Owalo
Nelson Owalo

Reputation: 2414

Import Module in ES6 Class Function

I have migrated my project to ESM and thus using .mjs in all my files in nodejs.

Previously in CommonJs, I could require a file right in the middle of a ES6 class function in order to load it only when needed.

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

But now when using Michael Jackson Scripts a.k.a .mjs, I cannot import a file on demand:

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

My app has many files/modules that are not consumed immediately, and can more can always be added in future, thus hardcoding the imports at the begining of the file is not an option.

Is there a way to import the files dynamically on demand when needed?

Upvotes: 1

Views: 2162

Answers (1)

Nelson Owalo
Nelson Owalo

Reputation: 2414

With a little modification from this answer, I managed to get it working via:

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

Or you can use a promise if you are into that:

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

This suits me for now until the spec if finalised and shipped

Upvotes: 1

Related Questions