简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM