简体   繁体   English

Node.js惰性需求模块

[英]Node.js lazy require module

I'm writing a lazy module require() or import 我正在写一个懒惰的模块require()或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: console.log语句记录:

lazy require {target: {…}, name: "./Linking"} 懒惰的要求{target: {…}, name: "./Linking"}

So require(name) should be getting called as: require("./Linking") 因此require(name)应该被调用为: require("./Linking")

Not as require(".") which the error is indicating. 错误所指示的不如require(".")

Found a related bug report: 找到了相关的错误报告:

https://github.com/webpack/webpack/issues/4921 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. 由于节点require树解析度是静态评估/分析的,因此webpack假定这样做,因此无法进行动态解析。

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. 另外,在浏览器上,Webpack必须在运行浏览器之前先翻译所需的包,这样动态惰性需求就无法在编译后运行。 You'd be missing the transpiled source of that required module. 您将缺少该必需模块的转译源。

I've tried using import() but it also has bugs: 我尝试使用import()但它也有错误:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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