我正在Electron中创建一个hello world项目,发现我可以在Main流程https://electronjs.org/blog/typescript中使用Typescript。
它说使用Typescript将文件扩展名从index.js更改为index.ts,然后更新package.json以指向新脚本:
{
"name": "electrontypescript",
"version": "1.0.0",
"description": "Typescript and Electron",
"main": "index.ts",
"scripts": {
"start": "electron ."
},
"devDependencies": {
"electron": "^5.0.1"
},
"dependencies": {
"lodash": "^4.17.11"
}
}
它可以工作,但是当我添加自己的类时,它会引发错误。
index.ts的顶部:
const { TypeHouse } = require ("./TypeHouse");
TypeHouse.ts:
function test() {
}
export class Cat {
}
export class TypeHouse {
public status: String = "ready";
private _output: String = "";
readonly startTime = Date.now();
private running: Boolean = false;
constructor(private _message: String, private _prompt: String) {
this.setStatus(_message);
}
async execute(): Promise<void> {
try {
//await CommandExecutor.execute(this);
} catch (exception) {
this.handleError(exception);
} finally {
//this.emit("end");
}
}
handleError(message: TypeHouse | string): void {
this.setStatus("Status.Failed");
if (message) {
//
}
}
isRunning(): boolean {
return this.running !== false;
}
public setStatus(value: String) {
this._output = value;
}
}
module.exports = {TypeHouse, Cat};
Package.json:
{
"name": "electron-app",
"version": "1.0.0",
"description": "Electron",
"main": "index.js",
"scripts": {
"start": "electron ."
},
"devDependencies": {
"electron": "^5.0.1",
"typescript": "^3.5.1"
},
"dependencies": {
"lodash": "^4.17.11"
}
}
错误消息:
应用程序在加载期间引发错误错误:找不到模块“ ./TypeHouse” 需要堆栈: -/用户/项目/ElectronApp/index.ts -/Users/projects/ElectronApp/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar/main.js
如果要使用,我正在使用Visual Studio Code(它会在控制台中引发错误)。
答案 0 :(得分:1)
Electron提供类型声明,而不提供直接运行TypeScript的能力。在运行之前,我们仍然需要将TypeScript转换为JavaScript。
main
指向index.js
。npm start
。在步骤(2)中,我们将index.ts和TypeHouse.ts文件转换为JavaScript。这是开始将TypeScript转换为Javascript的方法。在您的项目目录中,运行以下命令:
npm install -g typescript
tsc --init // create a tsconfig.json file with reasonable default values
tsc // transpile your TypeScript to JavaScript
npm start // run the output index.js file
嗯...您将npm run构建放在哪里?是否替换start属性中的值?我已经用package.json更新了帖子
{
"name": "electron-app",
"version": "1.0.0",
"description": "Electron",
"main": "index.js",
"scripts": {
"build": "tsc", <--------------------------
"start": "electron ."
},
"devDependencies": {
"electron": "^5.0.1",
"typescript": "^3.5.1"
},
"dependencies": {
"lodash": "^4.17.11"
}
}
从那里,您可以从命令行执行npm run build
,与执行./node_modules/.bin/tsc
等效。