如何在 Electron 上使用具有 TypeScript 类型支持的内部函数或条件?

问题描述

Electron Performance docs中,如下所述:

在传统的 Node.js 开发中,我们习惯于将所有 require() 语句放在顶部。如果您目前正在使用相同的策略编写 Electron 应用程序,并且正在使用您并不立即需要的大量模块,请应用相同的策略并将加载推迟到更合适的时间。

因此建议“及时”分配资源,在需要时调用 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 });
}

它在 @typescript-eslint/no-unsafe-call 中有一个 ESLint 错误Unsafe call of an any typed value.eslint(require('electron-debug'))”,即使 this library has types defined。 >

但是如果用 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),因此我们可以假设它仍然使用 Electron 文档中提到的 require cache


将这种方法与 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);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...