Adding custom TypeScript classes to an Electron project is a straightforward process that allows developers to enhance their

Currently working on a hello world project in Electron and stumbled across the possibility of using Typescript for the Main process, .

The provided instructions suggest changing the file extension from index.js to index.ts and updating the package.json file to point to the new script:

{
  "name": "electrontypescript",
  "version": "1.0.0",
  ...
}

Following these steps enabled me to get it up and running, but when I attempted to add my own class, errors started popping up.

The beginning of index.ts looks like this:

const { TypeHouse } = require ("./TypeHouse");

In the TypeHouse.ts file, there's some code defining classes and methods implemented. However, upon execution, an error is thrown stating that it cannot find the module './TypeHouse'.

Moreover, the error message revealed:

App threw an error during load Error: Cannot find module './TypeHouse' Require stack: - /Users/projects/ElectronApp/index.ts - /Users/projects/ElectronApp/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar/main.js

It's worth noting that I'm utilizing Visual Studio Code, where the error appears in the console.

Answer №1

While Electron provides type declarations, it does not run TypeScript directly. Before running TypeScript code, we must transpile it to JavaScript.

  1. Maintain your main file as index.js.
  2. Transpile your TypeScript code.
  3. Execute npm start.

During step (2), we will convert the index.ts and TypeHouse.ts files into JavaScript format. To begin transpiling TypeScript code to Javascript, follow these steps in your project directory:

npm install -g typescript
tsc --init        // generates a tsconfig.json file with default settings
tsc               // transpile TypeScript code to JavaScript
npm start         // execute the generated index.js file 

Where should I include npm run build? Should I replace the value of the start property in package.json? I have updated the post with details about package.json

{
  "name": "electron-app",
  "version": "1.0.0",
  "description": "Electron Application",
  "main": "index.js",
  "scripts": {
    "build": "tsc",             <--------------------------
    "start": "electron ."
  },
  "devDependencies": {
    "electron": "^5.0.1",
    "typescript": "^3.5.1"
  },
  "dependencies": {
    "lodash": "^4.17.11"
  }
}

You can then use npm run build in the command line, which is equivalent to ./node_modules/.bin/tsc.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to create a dynamic URL linking to an external site in Angular 5?

When attempting to create a link like this: <a [href]="getUrl()">click me</a> getUrl() { return this.domSanitizer.bypassSecurityTrustUrl('http://sampleUrl.com'); } The link is not clickable. When hovering over the ...

"Exploring the world of TypeScript Classes in combination with Webpack

If I create a TypeScript class with 10 methods and export a new instance of the class as default in one file, then import this class into another file (e.g. a React functional component) and use only one method from the class, how will it affect optimizati ...

Using the expect statement within a Protractor if-else block

My script involves an if-else condition to compare expected and actual values. If they do not match, it should go to the else block and print "StepFailed". However, it always executes the if block and the output is "step passed" even when expected does not ...

When using electron-build, the node-adodb encountered an error stating: 'Failed to spawn C:WINDOWSSysWOW64cscript.exe'

Utilizing node-adodb.js for reading .mdb files with the following code: const db = require('node-adodb') ipcMain.on('query', (e, p) => { if (!p) return appendFileSync('a.log', new Date().getTime() + ' ' + p.t ...

The Angular/Typescript framework encountered an issue when trying to locate a differ that can handle an object of type 'object'. NgFor is limited to binding with Iterables like Arrays and is not compatible with plain objects

I am currently utilizing Angular for my project. I am attempting to call an API to fetch data from it, but I keep encountering this error: core.js:4352 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object&ap ...

Guide on organizing the Object into a precise structure in Angular

I am looking to transform the current API response object into a more structured format. Current Output let temp = [ { "imagePath": "", "imageDescription": [ { "language": "en ...

Bind the change event of an Angular input to a variable that contains a custom function

Is there a way to achieve something similar to the following? <input (input)="doSomething($event)" /> <input (input)="boolVar = $event.target.value > 5" /> I would like to accomplish it by defining a function, like this: funcVar = (e) =&g ...

Steps for incorporating a new element in Reactjs

While attempting to insert a new element into a React object, I encountered the following issue: const isAdmin = true let schema = { fname: Yup.string().required('Required'), lname: Yup.string().required('Required&apo ...

Utilize API within an array to enable Ionic to display a PDF in a document viewer

Recently diving into the world of Angular and Ionic, I've come across some interesting API data: [{"ID":"1","Title":"Maritime Safety","File_Name":"9c714531945ee24345f60e2105776e23.pdf","Created":"2018-11-07 17:36:55","Modified":"2018-11-07 17:36:55"} ...

Issue with PrimeNG dropdown where selected option gets reset when bound to interface property

Here is how I have implemented the p-dropdown: <p-dropdown name="taxOptions" [options]="taxOptions" [(ngModel)]="purchaseInvoiceDetail.tax"></p-dropdown> The values for the taxOptions property are set like this: this.taxOptions = [ { l ...

Is it Possible for Angular Layout Components to Render Content Correctly even with Deeply Nested ng-container Elements?

Within my Angular application, I have designed a layout component featuring two columns using CSS. Within this setup, placeholders for the aside and main content are defined utilizing ng-content. The data for both the aside and main sections is fetched fr ...

Error: In Angular and Typescript, the function this.$resource is not recognized

I keep encountering a TypeError: this.$resource is not a function. Below is the code snippet causing the issue: export class DataAccessService implements IDataAccessService { static $inject = ["$resource"]; constructor(private $resource: ng ...

Breaking down arrays in Typescript

Let's say I have an array like this: public taskListCustom: any=[ {title: 'Task 1', status: 'done'}, {title: 'Task 2', status: 'done'}, {title: 'Task 3', status: 'done'}, {title: 'Task ...

Creating various import patterns and enhancing Intellisense with Typescript coding

I've been facing challenges while updating some JavaScript modules to TypeScript while maintaining compatibility with older projects. These older projects utilize the commonjs pattern const fn = require('mod');, which I still need to accommo ...

Dealing with Scoping Problems in a Typescript d3 Update Tutorial

I'm facing challenges trying to implement the provided bl.ocks example in Typescript (using Angular). This is my implementation in TypeScript: StackBlitz Could anyone offer insights on what might be causing the issues I'm encountering? My initi ...

What is the reason for TS expressing dissatisfaction about the use of a type instead of a type entry being provided

Below is a snippet of code for a Vue3 component that takes in an Array of Objects as a prop: <script lang="ts"> interface CorveesI { What: string, Who: string, Debit: number } export default { name: 'Corvees', props: { ...

What is the best way to incorporate an exported TypeScript class into my JavaScript file?

One of my JavaScript files is responsible for uploading a file to Microsoft Dynamics CRM. This particular JavaScript file makes use of RequireJS to reference another JavaScript file. The referenced JavaScript file, in turn, was compiled from multiple Typ ...

Encountering an error in Angular 4: 'Cannot find property on specified component type'

I recently embarked on the journey of learning Angular 4 and TypeScript, but I've encountered my first obstacle. My current challenge involves creating a simple date and time component. Despite having a seemingly correct Javascript code, I believe I ...

What is the method for implementing a custom layout for the items within a Select component?

I want to customize the options of a Select component by adding HTML elements. Here is an example: <mat-select [(ngModel)]="items"> <mat-option *ngFor="let item of ($items | async)" [value]="item.id"> <span>{{item.name}}</span&g ...

Having trouble accessing store state in Angular with NGXS

In the parent component, I am dispatching an action and hoping to receive the dispatched array in the child component. To achieve this, I have implemented the following code: export class ListComponent implements OnInit { @Select(ProductState.getProductD ...