簡體   English   中英

ElectronJS,JavaScript和Python-未定義require嘗試了所有選項

[英]ElectronJS, JavaScript and Python - require is not defined tried all the options

我在嘗試執行以下行時遇到問題:

var path = require('path') 

我得到

Uncaught ReferenceError: require is not defined

一切都很好,除了需要錯誤,為什么?

我有3個文件:

translate.js:

function get_translate(){
var path = require('path') 
var trans = document.getElementById("trans").value
document.getElementById("trans").value = ""

var options = {
scriptPath : path.join(__dirname, '/../engine/'),
args : [trans]
}
translate = PythonShell.run('translate_engine.py', options);
translate.on('message', function(message) {
swal(message);
})
}

translate.html:

<head>
<link rel="stylesheet" 
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
</script>
<script src="linkers/translate.js"></script>
</head>

<body>
<br>
<div class="container">
<button="btn btn-info"><a style="color:white" href="gui.html">Back</a> 
</button>

<div class="jumbotron">
  <h1>Translate App</h1>
  <br>
  <label>Enter you word here</label>
  <input id="trans" type="text" placeholder="Text"/>
  <button class="but but-success" onclick="get_translate()">Go</button>
</div>
</body>

translate_engine.py:

import sys
trans = sys.argv[1]
print(trans)
sys.stdout.flush()

謝謝

您是否要在電子BrowserWindow中執行此代碼?

如果是,請在啟動BrowserWindow時檢查nodeIntegration是否未設置為false

mainWindow = new BrowserWindow({
  minWidth: 370,
  minHeight: 520,
  webPreferences: {
    nodeIntegration: true,
  },
});

默認情況下, nodeIntegration實際上是true的,因此您也可以刪除此行–我只是想使其變得非常明顯;)

只要nodeIntegrationtrue ,就可以在電子渲染過程中運行任何 nodeJS代碼。

這超出了您最初提出的問題,並且更加高級,但是如果您不想啟用此功能,因為它帶來了許多安全性問題 ,則可以將某些nodeJS方法公開給呈現過程。 您可以使用預加載腳本執行此操作。

mainWindow = new BrowserWindow({
  ...
  webPreferences: {
    nodeIntegration: false,
    preload: path.join(__dirname, 'preload.js') // here you can re-expose certain methods such as `require`
  },
});

preload String(可選)-指定將在頁面中其他腳本運行之前加載的腳本。 無論打開還是關閉節點集成,此腳本始終可以訪問節點API。 該值應該是腳本的絕對文件路徑。 關閉節點集成后,預加載腳本可以將節點全局符號重新引入全局范圍。

更多信息可以在這里找到: https//electronjs.org/docs/api/process#event-loaded

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM