将 node require 与 Electron 和 Webpack 一起使用 [英] Using node require with Electron and Webpack

查看:21
本文介绍了将 node require 与 Electron 和 Webpack 一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在这个应用程序中,我需要在运行时动态 require 一些在构建时不存在的文件.代码如下所示:

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.

我尝试过使用externals"配置选项,但由于这是一个动态要求,它似乎没有被externals"处理.

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

这篇关于将 node require 与 Electron 和 Webpack 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆