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?

Nelson Owalo
  • 2,324
  • 18
  • 37
  • 1
    [Dynamic import](https://github.com/tc39/proposal-dynamic-import) is still only a proposal. I don't what browsers are currently supporting it. – zero298 Aug 01 '18 at 14:12
  • You still can use `require` if your environment still supports it, otherwise use dynamic `import`. – Bergi Aug 01 '18 at 15:18
  • @Bergi Cant use require, I'm running nodejs with the `--experimental-modules` flag – Nelson Owalo Aug 01 '18 at 15:25

1 Answers1

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

Nelson Owalo
  • 2,324
  • 18
  • 37