目前我正在进行个人项目,我正在使用Electron和Typescript,目前我的Main.js和Renderer.js都是正在编译的Typescript文件。所以Main.ts和一个webpack捆绑了React Typescript应用程序。我当前的问题是,每当我尝试在我的模板(main.html)中设置变量“remote”时,它当前在模板内部工作,但是我无法访问我的Typescript应用程序中的“远程”变量。我将在下面演示:
// Template - main.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>League Desktop</title>
</head>
<body>
<div id="mount"></div>
<script src="../node_modules/react/dist/react.js"></script>
<script src="../node_modules/react-dom/dist/react-dom.js"></script>
<script type="text/javascript">
window.remote = require('electron').remote;
console.log(remote); // Returns object and works inside this script tag
<script src="http://localhost:8080/static/main.bundle.js"></script>
</body>
</html>
然而正如我所提到的,即使返回一个对象并在脚本标记内工作;它在我的应用程序中不起作用。这很有趣,因为我记得前一段时间做了一个项目,这完美无瑕。我目前的解决方法是将“远程”模块导入到我的实际文件/类中,然后才能使用它,同时使用两个不同的webpack配置,其中一个用于具有“target:'electron-renderer'”的React应用程序和一个用于具有“目标:'电子主''的主电子应用程序。观察到这种方法在没有不同配置和正确目标的情况下不起作用。所以这不会起作用:
// TitleBar.tsx
import * as React from "react";
import { Component } from "react";
export default class TitleBar extends Component<any, any> {
public _close(){
remote.getCurrentWindow().close(); // This does not work!
// Without webpack targets and using global variables in template!
}
public render() {
return <button onClick={this._close}>Close Window</button>;
}
}
请注意,如果不向webpack添加“目标”,则远程或任何其他电子模块实际上不会加载。假设设定了适当的“目标”;这应该有效:
// TitleBar.tsx
import * as React from "react";
import { Component } from "react";
import { remote } from "electron";
export default class TitleBar extends Component<any, any> {
public _close(){
remote.getCurrentWindow().close(); // This works now!
// With proper webpack targets and no global variables in template!
}
public render() {
return <button onClick={this._close}>Close Window</button>;
}
}
这已经很长了所以我会很快结束它,但为什么它不像我记得的那样工作?是Webpack还是打字稿阻碍了我?可以想象,每次我需要它时都会为“远程”添加导入会很烦人,比如React。
无论如何,谢谢你的时间,我希望你能帮助我!
答案 0 :(得分:1)
将远程引用存储在主文件中的全局对象上。 你可以这样做: -
global.remote = remote; // import remote as it works for you prior to this statement.
此后您也可以在其他ts文件中引用此内容而无需导入。但是你必须使用global.remote而不是直接使用远程