如何在 Electron 上使用 require 内部函数或条件以及 TypeScript 类型支持?

How can I use require inside functions or conditions with TypeScript type support on Electron?

Electron Performance docs中表示如下:

In traditional Node.js development, we're used to putting all our require() statements at the top. If you're currently writing your Electron application using the same strategy and are using sizable modules that you do not immediately need, apply the same strategy and defer loading to a more opportune time.

因此它建议在需要时调用 require() “及时”分配资源。问题是我正在尝试使用 electron-react-boilerplate 而 TypeScript 似乎不支持这种代码。这是一个例子:

src/main.dev.ts:

if (
  process.env.NODE_ENV === 'development' ||
  process.env.DEBUG_PROD === 'true'
) {
  require('electron-debug')({ showDevTools: false });
}

它有一个 ESLint 错误“任何类型值的不安全调用。eslint(@typescript-eslint/no-unsafe-call)”在 require('electron-debug') 中,即使 [=25] =].

但是,如果将其替换为 import,则可以正常工作而不会出现该错误:

import electronDebug from 'electron-debug'; // at the top of the file

if (
  process.env.NODE_ENV === 'development' ||
  process.env.DEBUG_PROD === 'true'
) {
  electronDebug({ showDevTools: false });
}

那么在那种情况下如何使用 require 类型支持?

我读到 this answer 说要使用 import module = require('module') 但随后发生错误,说“导入声明只能在命名空间或模块中使用。ts(1232)" 如果我​​在 if 或函数中使用它。

我们可以使用异步 import() 来解决这个问题:

if (
  process.env.NODE_ENV === 'development' ||
  process.env.DEBUG_PROD === 'true'
) {
  import('electron-debug').then(electronDebug =>
    electronDebug.default({ showDevTools: false }),
  );
}

请注意,对于 CommonJS,它将被转译为 require(阅读更多关于它 here), so we can assume that it still uses the require cache 的信息,在 Electron 文档中提到。


将此方法与 electron-react-boilerplate 一起使用可能会在 yarn package 上创建额外的文件,例如 252.main.prod.js,这将在尝试执行程序时导致错误 (错误:找不到模块'../../src/252.main.prod.js')。为避免它,您需要告诉 Webpack 忽略它,如下例所示:

之前:

const sourceMapSupport = require('source-map-support');
sourceMapSupport.install();

之后:

import(/* webpackIgnore: true */ 'source-map-support')
  .then((sourceMapSupport) => sourceMapSupport.install())
  .catch(console.error);