如何在 React Typescript 应用程序中使用 Electron BrowserWindow

IT技术 reactjs typescript electron
2022-07-22 01:45:24

我目前正在尝试找到一种将第三方 URL(例如 disney+ 或 spotify)集成到我的应用程序中的方法。我很快发现它是不可能的iframe,因为许多网站都在阻止它。我的下一个想法是使用Electron's webview标签。然而,这已经贬值了。

现在我有了将 Electron 集成BrowserWindow到 React Dom 中的想法。所以基本上,写一个electron React application

https://medium.com/folkdevelopers/the-ultimate-guide-to-electron-with-react-8df8d73f4c97

如果我按照本指南导入所有内容,我会收到此错误。

App.tsx:2 Uncaught TypeError: window.require is not a function

我知道这是typescript..需要...不是解决方案。但是导入也不起作用。我还尝试构建一个普通的 javascript 应用程序来测试它,但效果不佳。

我也确信即使我得到正确的导入,我也应该得到一个constructor error. 有没有人有这个问题的经验,可以请帮助我。

电子主干

import { app, BrowserWindow } from 'electron'
import * as path from 'path'
import installExtension, {
  REACT_DEVELOPER_TOOLS,
} from 'electron-devtools-installer'

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // contextIsolation: false,
      preload: path.join(__dirname, 'preload.js'),
    },
  })

  if (app.isPackaged) {
    // 'build/index.html'
    win.loadURL(`file://${__dirname}/../index.html`)
  } else {
    win.loadURL('http://localhost:3000/index.html')

    win.webContents.openDevTools()

    // Hot Reloading on 'node_modules/.bin/electronPath'
    require('electron-reload')(__dirname, {
      electron: path.join(
        __dirname,
        '..',
        '..',
        'node_modules',
        '.bin',
        'electron' + (process.platform === 'win32' ? '.cmd' : '')
      ),
      forceHardReset: true,
      hardResetMethod: 'exit',
    })
  }
}

app.whenReady().then(() => {
  // DevTools
  installExtension(REACT_DEVELOPER_TOOLS)
    .then((name) => console.log(`Added Extension:  ${name}`))
    .catch((err) => console.log('An error occurred: ', err))

  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })

  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      app.quit()
    }
  })
})

应用程序.tsx

import './App.css'
const electron = window.require('electron')
const remote = electron.remote
const { BrowserWindow } = remote

function App() {
  return (
    <div className='App'>
      <h1>halllo</h1>
      <button
        onClick={() => {
          let win = new BrowserWindow()
          win.loadURL('https://www.electronjs.org/docs/api/remote')
        }}
      >
        Open BrowserWindowss
      </button>
    </div>
  )
}

export default App

react tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "outDir": "../build", // Output transpiled files to build/electron/
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}
2个回答

在 main.ts 中:

 webPreferences: {
   nodeIntegration: true,
   contextIsolation: false,
   enableRemoteModule: true,
   preload: path.join(__dirname, 'preload.js'),
},

我正在使用它,它工作正常:

它用于requiremain.tsimportReact 代码中使用。

它的使用import意味着所需的module在构建时由 Webpack 包含在渲染器包中,而不是在运行时从您的Node.js环境中加载。

它根本不使用window.require(因此,我知道没有问题)。


或者有这个(我没有使用):

它谈到使用window.require

我们需要使用 导入 ipcRenderer modulewindow.require,因为我们希望在运行时从节点环境中获取电子,而不是在 webpack 编译期间使用的电子。此处链接到 github 问题

我不知道它为什么要在运行时而不是在编译期间要求。

它链接到此问题,该问题已关闭并有 93 条评论: