原谅我的原告问题的简单性,我已经接近我的智慧了。
我正在寻找一个 Electron v8 和 TypeScript 的简单示例。它不需要包括 WebPack、Babel、React 或其他任何东西。我发现的任何东西似乎都不适用于 Electron v8。
更新
我之前的陈述让我想起了麦克白的台词,这是一个故事
一个白痴说的,充满了声音和愤怒,没有任何意义,所以让我们在中陈述问题详情 这次。
stock Electron & Typescript example没有证明以下内容:
import
渲染器进程中的节点模块import
对于渲染器进程中我自己的应用程序模块。 尝试这样做没有来自
tsc
的错误但引发了运行时错误ReferenceError: exports is not defined[Learn More]
exports.__esModule = true
使用
require
而不是 import
,尤其是对于像 EventEmitter
这样的类打乱 VS Code 警告'EventEmitter' refers to a value, but is being used as a type here.ts(2749)
......所以这是一个倒退的步骤。
设置
target
在 tsconfig.json
至ES2018
意味着我可以使用 ES6 模块和 import
我自己的模块的语法,虽然它需要 .js
工作的后缀。import {blah} from './MyModule.js'` // Shouldn't need that suffix!
VS Code 给人的感觉是我可以
import
节点模块,但它在运行时仍然失败。Uncaught TypeError: Failed to resolve module specifier "events". Relative references must start with either "/", "./", or "../".
最佳答案
你需要四样东西:package.json
, tsconfig.json
, index.ts
和 index.html
.
我的示例基于 Electron tutorial和一篇关于使用 Electron and TypeScript 的博文.package.json
需要引入 Electron 和 TypeScript 依赖,触发 TypeScript 构建并启动 Electron。
{
"name": "electron-ts",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"prestart": "tsc",
"start": "electron ."
},
"devDependencies": {
"electron": "8.0.1",
"typescript": "3.7.5"
}
}
预启动脚本编译 TypeScript 并使用项目作为应用程序目录开始运行 Electron。我不知道所需的 TypeScript 的最低版本,但它是 3 的东西。
tsconfig.json
需要设置一些编译器选项并确定运行时要构建的内容tsc
.{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"noImplicitAny": false,
"suppressImplicitAnyIndexErrors": true
},
"exclude": ["node_modules"]
}
这将编译它在
node_modules
之外找到的所有 TypeScript 文件。并在它们旁边生成 JavaScript。index.ts
需要创建一个浏览器窗口并加载登录页面。import { app, BrowserWindow } from 'electron';
function createWindow () {
let win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile('index.html');
}
app.allowRendererProcessReuse = true;
app.whenReady().then(createWindow);
这是一些启动 Electron 的样板代码,所有类型都被推断出来。
最后是
index.html
需要展示一些你可以识别的东西。<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag -->
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Hello World!</h1>
We are using node <script>document.write(process.versions.node)</script>,
Chrome <script>document.write(process.versions.chrome)</script>,
and Electron <script>document.write(process.versions.electron)</script>.
</body>
</html>
这将显示 node、Chrome 和 Electron 的版本。
将这些文件放在同一目录中,运行
npm start
应该编译 TypeScript 并启动 Electron 应用程序。
关于typescript - 寻找 Electron v8 和 TypeScript 的 _working_ 简单示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60283564/