Search code examples
node.jsmodulelazy-loadingrequire

Node.js lazy require module


I'm writing a lazy module require() or import

const lazy = new Proxy({}, 
  {
    get: function (target, name) {
      console.log('lazy require', { target, name })
      return require(name)
    }
  }
)

/**
  * @param {string} Module Name
  * @example const expo = requirez('expo')
  */
export default function requirez(name) {
    return lazy[name]
}

and oddly when I run it I get:

Cannot find module "."

The console.log statement logs:

lazy require {target: {…}, name: "./Linking"}

So require(name) should be getting called as: require("./Linking")

Not as require(".") which the error is indicating.


Solution

  • Found a related bug report:

    https://github.com/webpack/webpack/issues/4921

    Since node require tree resolution is evaluated/analyzed statically and webpack assumes this it fails on dynamic resolution.

    Also, on browser webpack will have to transpile the required bundle before running in the browser thus dynamic lazy requires can't be run after transpilation. You'd be missing the transpiled source of that required module.

    I've tried using import() but it also has bugs:

    https://github.com/webpack/webpack/issues/4292#issuecomment-280165950