问题描述
尝试执行以下行时出现问题:
I have a problem when I try to execute the following line:
var path = require('path')
我得到
Uncaught ReferenceError: require is not defined
除了require错误外,其他所有方法都可以正常工作,为什么?
all work fine except from require error, why?
我有3个文件:
translate.js:
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:
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:
translate_engine.py:
import sys
trans = sys.argv[1]
print(trans)
sys.stdout.flush()
谢谢
推荐答案
您是否要执行
如果是,请检查 nodeIntegration
是否未设置为<$ c $初始化 BrowserWindow
时c> false 。
If yes, check if nodeIntegration
isn't set to false
when initiating the BrowserWindow
.
mainWindow = new BrowserWindow({
minWidth: 370,
minHeight: 520,
webPreferences: {
nodeIntegration: true,
},
});
nodeIntegration
实际上是 true
默认情况下,因此您也可以删除此行–我只是想使其非常明显;)
nodeIntegration
is actually true
by default, so you can remove this line as well – I'm just trying to make it super obvious ;)
由于 nodeIntegration
是 true
,因此您可以在电子渲染过程中运行任何 nodeJS代码。
As long as nodeIntegration
is true
you can run any nodeJS code in the electron render process.
这超出了您最初的问题,并且更加高级,但是如果您不想启用它,因为它附带了许多,您可以将某些nodeJS方法暴露给渲染过程。您可以使用预加载脚本来做到这一点。
This goes beyond your initial question and it's a little bit more advanced, but If you don't want to enable this as it comes with numerous security issues, you can just expose certain nodeJS methods to the render process. You can do this with a preload script.
mainWindow = new BrowserWindow({
...
webPreferences: {
nodeIntegration: false,
preload: path.join(__dirname, 'preload.js') // here you can re-expose certain methods such as `require`
},
});
更多信息可以在此处找到:
More infos can be found here:https://electronjs.org/docs/api/process#event-loaded
这篇关于ElectronJS,JavaScript和Python-未定义require尝试了所有选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!