5

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?

Michael Bromley
  • 4,792
  • 4
  • 35
  • 57

2 Answers2

6

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
});
Michael Bromley
  • 4,792
  • 4
  • 35
  • 57
  • I tried using this in a electron vue app. But it says `global.require` is not a function. Any idea what could go wrong here ? – turbopasi Jun 16 '20 at 08:02
  • That `global.require` is something Electron is making available. It doesn't work when you're using Node.js itself. – Kevin Ghadyani Feb 19 '21 at 22:04
-1

I came across this article and for some other reason the author needs node modules which gets not transpiled by webpack. He suggested to use

new webpack.IgnorePlugin(new RegExp("^(fs|ipc)$"))

in the webpack.config.js file. This should prevent to transpile the module fs and ipc so it can be used (required) in code.

I am not really sure if this hits also your problem but it might help.

The original article for more context can be found here: https://medium.com/@Agro/developing-desktop-applications-with-electron-and-react-40d117d97564#.927tyjq0y

silverfighter
  • 6,762
  • 10
  • 46
  • 73