无法在 Electron 中的单独 js 文件中使用 require

问题描述 投票:0回答:1

我有一个非常简单的 Electron 应用程序,使用版本 5.0.1。

这是我的

index.html
文件:

<!DOCTYPE html>
<html>
  <head>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
    <meta content="utf-8" http-equiv="encoding">
    <title>Webgl</title>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/104/three.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
      <script src="./initialization.js"></script>
      <link rel="stylesheet" type="text/css" href="application.css">
  </head>

  <body>

  <script>
        
    initialization();

  </script>
</html>

然后我的

main.js
文件:

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

let win

function createWindow () {
  // Create the browser window.
  win = new BrowserWindow({ width: 1280, 
                            height: 720, 
                            nodeIntegration: true, 
                            resizable: false,
                            maximizable: false })

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

  // Open the DevTools.
  win.webContents.openDevTools()

  // Emitted when the window is closed.
  win.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null
  })
  
}

app.on('ready', createWindow)

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

app.on('activate', () => {
  if (win === null) {
    createWindow()
  }
})

我的

package.json
文件:

{
  "name": "estimation",
  "version": "1.0.0",
  "description": "estimation app",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
     "electron": "^5.0.1"
  }
}

然后是我的

inittialization.js
文件,其中包含
initialization()
方法和
const fs = require('fs')
;

const fs = require('fs');

function initialization(){
}

现在我在多个地方问过同样的问题,我尝试了多种解决方案,但没有任何效果。我想知道现阶段这是否是一个 Electron 错误。

我无法摆脱的错误,无论我做什么,我都会遇到这个错误

Uncaught ReferenceError: require is not defined

我只是想在另一个JS文件中使用require。为什么 Node.js 或 Electron 不接受这个?

javascript node.js electron
1个回答
1
投票

将 nodeIntegration 放置在 webPreferences 属性中

{ width: 1280,
 height: 720,
 webPreferences : { nodeIntegration: true }, 
 resizable: false,
 maximizable: false
 }
© www.soinside.com 2019 - 2024. All rights reserved.