注入的主脚本中的 require(id) 不是基于文件的


¥require(id) in the injected main script is not file based

注入的主脚本中的 require() 与未注入的模块可用的 require() 不同。除 require.main 外,它也不具有非注入 require() 所具有的任何属性。它只能用于加载内置模块。尝试加载只能在文件系统中找到的模块将引发错误。

¥require() in the injected main script is not the same as the require() available to modules that are not injected. It also does not have any of the properties that non-injected require() has except require.main. It can only be used to load built-in modules. Attempting to load a module that can only be found in the file system will throw an error.

用户可以将他们的应用打包到一个独立的 JavaScript 文件中以注入可执行文件,而不是依赖于基于 require() 的文件。这也确保了更具确定性的依赖图。

¥Instead of relying on a file based require(), users can bundle their application into a standalone JavaScript file to inject into the executable. This also ensures a more deterministic dependency graph.

但是,如果仍然需要基于 require() 的文件,也可以实现:

¥However, if a file based require() is still needed, that can also be achieved:

const { createRequire } = require('node:module');
require = createRequire(__filename);