在Electron和Webpack中使用节点需求

在Electron和Webpack中使用节点需求

本文介绍了在Electron和Webpack中使用节点需求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Electron构建一个项目,并使用Webpack来构建(Angular 2)渲染过程应用。

I am building a project with Electron, and using Webpack to build the (Angular 2) render process app.

在此应用中,我需要动态地需要在运行时一些在构建时不存在的文件。代码看起来像这样:

In this app, I need to dynamically require some files at run-time which do not exist at build-time. The code looks something like this:

require("fs").readdirSync(this.path).forEach(file => {
  let myModule = require(path.join(this.path, file));
  // do stuff with myModule
});

问题是Webpack编译器将转换 require()调用其自己的 __ webpack_require __(),并在运行时在其内部模块注册表中查找动态 myModule文件,以及当然不会找到它。

The problem is that the Webpack compiler will convert the require() call to its own __webpack_require__() and at run-time, it will look in its own internal module registry for the dynamic "myModule" file, and of course will not find it.

我尝试使用外部配置选项,但是由于这是一个动态要求,因此似乎不会由

I have tried using the "externals" config option, but since this is a dynamic require, it doesn't seem to be processed by "externals".

还有其他人成功解决了这个问题吗?

Anyone else had success in solving this problem?

推荐答案

正如@jantimon在对我的问题的评论中所建议的那样,解决方案是使用 global.require

As suggested in a comment to my question by @jantimon, the solution is to use global.require:

require("fs").readdirSync(this.path).forEach(file => {
  let myModule = global.require(path.join(this.path, file));
  // do stuff with myModule
});

这篇关于在Electron和Webpack中使用节点需求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 11:11