<script> require('renderer.js') </script> - 不连接js文件

<script> require('renderer.js') </script> - does not connect the js file

我正在尝试使用 Electron 在主渲染器和渲染器之间组织 IPC。正如说明所说,我应该将脚本(见标题)添加到 index.html。但它看起来不像是加载的。 rendeder.js 中的任何内容都不会执行。

本教程 https://www.brainbell.com/javascript/ipc-communication.html 是互联网上关于该主题最详细的教程。其他人只是在他们的文章中跳过了太多信息,以至于学习者根本无法在应用程序中重现它。

我试过了:

<script> 
    require('renderer.js')
</script>

<script>
    require('./renderer.js')
</script>

<script src='renderer.js'>
</script>

等相似。

所以让我展示一下我所做的,也许这会有所帮助。

创建 window 的代码。注意 webPreferences 设置

app.on('ready', function () {
  mainWindow = new BrowserWindow({
    show: false,
    width: 1024,
    height: 768,
    backgroundColor: '#2C3E50',
    center: true,
    webPreferences: {
      nodeIntegration: true,
      devTools: true
    }
  })

如果没有 devtools,您将看不到错误输出或检查内容。还有其他方法可以通过菜单和键盘命令打开 devTools

然后,假设你已经通过npm安装了脚本或库,你可以在不指定路径的情况下执行以下操作,否则你将需要一个相对路径

const THREE = require('three')

我运行遇到同样的问题

首先,确保在启动应用程序时打开 nodeIntegration:

app.on('ready', _ => {
    mainWindow = new BrowserWindow({
        title: "My Electron App",
        backgroundColor: '#FFF',
        height: 800,
        width: 1200,
        center: true,
        webPreferences: {
            nodeIntegration: true // works on main window only
        }
    })

然后参考this answer.

玩多个选项,使用 requiresrc= 方法都有效。请参阅下面的附加内联注释。

<html>
  <head>
    <!-- make sure you have the semicolon after the require -->
    <!-- and make sure NOT to include the .js extension -->
      <script>require('./renderer');</script>
    <!-- make sure you include the extension -->
      <script src="./renderer.js" ></script>
  </head>
  <body>
    <!-- Put HTML first to avoid blocking -->
    <!-- All same options as in head work here, but shouldn't block -->
    <!-- In addition, async and defer might do something -->
    <!-- async should run script asynchronously, and defer wait until DOM loads -->
      <script src="./renderer.js" async></script>
      <script src="./renderer.js" defer></script>
  </body>
  <!-- scripts put here seems intermittent which runs first -->
</html>
<!-- scripts put here seems intermittent which runs first -->

有些会阻止 HTML 加载,直到脚本运行(我认为如果在 head 标记中,无论如何),而其他人似乎 运行dom HTML 将在脚本 运行 之前加载。我在 renderer.js 中使用警告框进行了测试,如果 运行 首先显示 window,它将阻止 window 显示 HTML 渲染。