简体   繁体   中英

Cannot use require in a separate js file in Electron

I have a very simple Electron app, using version 5.0.1.

Here is my index.html file:

<!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>

Then my main.js file:

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()
  }
})

my package.json file:

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

Then my inittialization.js file that contains the initialization() method and const fs = require('fs') ;

const fs = require('fs');

function initialization(){
}

Now I have asked the same question in multiple places, I have tried multiple solutions, nothing works. I am wondering if this is an Electron bug at this stage.

The error I can't get rid off and I keep getting whatever I do is this Uncaught ReferenceError: require is not defined

I simply want to use require in another JS file. Why is node.js or electron not picking this up ?

Place the nodeIntegration inside webPreferences attribute

{ width: 1280,
 height: 720,
 webPreferences : { nodeIntegration: true }, 
 resizable: false,
 maximizable: false
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM