如何在Electron上设置热重载

1,273 阅读1分钟

当在Electron应用程序上工作时,设置热重载是非常方便的,这样应用程序的更新就不需要重新启动。

你可以使用npm模块electron-reloader来做到这一点。

假设你有这样一个Electron应用程序的样本。

index.js

const { app, BrowserWindow } = require('electron')

function createWindow() {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
    },
  })

  // and load the index.html of the app.
  win.loadFile('index.html')
}

app.whenReady().then(createWindow)

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
  </body>
</html>

安装electron-reloader 作为开发依赖。

npm install -D electron-reloader

然后在index.js 文件中添加这一行。

try {
  require('electron-reloader')(module)
} catch (_) {}

就这样!现在,当你使用electron . ,或npm start ,如果你有

"start": "electron .",

在你的package.json ,你应用于应用程序文件的任何变化都将反映在应用程序窗口中。