Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using node require with Electron and Webpack

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
});

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?

like image 903
Michael Bromley Avatar asked May 20 '16 06:05

Michael Bromley


1 Answers

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
});
like image 117
Michael Bromley Avatar answered Sep 25 '22 15:09

Michael Bromley