首页 > 解决方案 > 如何在 Electron 项目中添加我自己的打字稿类

问题描述

我在 Electron 中创建了一个 hello world 项目,发现我可以将 Typescript 用于主进程,https: //electronjs.org/blog/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};

包.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'需要堆栈:-/Users/projects/ElectronApp/index.ts-/Users/projects/ElectronApp/node_modules/electron/dist/Electron.app/Contents/资源/default_app.asar/main.js

如果重要的话,我正在使用 Visual Studio Code(它会在控制台中引发错误)。

标签: typescriptvisual-studio-codeelectron

解决方案


Electron 提供类型声明而不是直接运行 TypeScript 的能力。在运行之前,我们仍然需要将 TypeScript 转换为 JavaScript。

  1. 保持你的main指向index.js
  2. 转译你的 TypeScript。
  3. 然后调用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.


推荐阅读