【发布时间】:2017-09-08 21:43:18
【问题描述】:
目前我正在做一个使用 Electron 和 Typescript 的个人项目,目前我的 Main.js 和 Renderer.js 都是正在编译的 Typescript 文件。所以 Main.ts 和一个 webpack 捆绑了 React Typescript 应用程序。我当前的问题是,每当我尝试在我的模板(main.html)中设置变量“remote”时,它当前正在模板中工作,但是我无法访问我的 Typescript 应用程序中的“remote”变量。我将在下面演示:
// 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 配置,其中一个用于具有“目标:'电子渲染器'”的 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 添加“目标”,remote 或任何其他电子模块实际上不会加载。假设设置了正确的“目标”;这应该工作:
// 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 还是 Typescript 阻碍了我?可以想象每次我需要时为“远程”添加一个导入会很烦人,比如 React。
无论如何,感谢您的宝贵时间,希望您能帮助我!
【问题讨论】:
标签: typescript webpack electron