1

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?

3
  • 1
    Dynamic import is still only a proposal. I don't what browsers are currently supporting it.
    – zero298
    Aug 1, 2018 at 14:12
  • You still can use require if your environment still supports it, otherwise use dynamic import.
    – Bergi
    Aug 1, 2018 at 15:18
  • @Bergi Cant use require, I'm running nodejs with the --experimental-modules flag Aug 1, 2018 at 15:25

1 Answer 1

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.