In my last post, I talked about how to Integrate Angular-CLI with Electron. One of the things that was missing was the use of Typescript, oposite to vanilla Javascript, though Electron’s main is a Node based engine, so almost everything about ES2015 and ES2016 should work, some newer features are still missing as current version, 1.7.11, is based on node 7.9. And, types are still missing, because of JavaScript. Using Electron with Typescript, is really simple, but we would need to install some modules.

Installing dependencies

We move to the Electron entry folder. In the case the you are integrating with Angular-CLI following my guide, it would be electron folder. Then, we run:

1
npm install -D typescript ts-node
  • typescript: Well, this is actually what we want to use.
  • ts-node: TypeScript execution environment and REPL for node. This will resolver all the .ts files on the fly.

Creating tsconfig.json

Run npx tsc --init if you are using npm 5.2+ to create the tsconfig.json. As is it will work, so we will leave it.

Updating files

We need to modify how the application runs.

  • Create a folder named src, this will be our development folder.
  • Move index.js to src and rename it index.ts. This is now a Typescript file.
  • Create a new index.js in the application root, with the following content.
    1
    2
    require('ts-node').register(); // This will register the TypeScript compiler
    require('./src'); // This will load our Typescript application

Running Electron

Now it’s time to try, and run npm start if you are following the integration guide, or electron . if you don’t have the associated script.

You should see something like this:
electron-error

This is fine. Because we are using __dirname as our folder root, now Electron can’t find the app source.

Updating index.ts

Hopefully, the solution is really simple. Just change __dirname in the path.join function with app.getAppPath().

What getAppPath() is? Docs
This is a Electron function that will resolve to the root of the application path.

Running Electron (again)

If everything went fine, you should now see your application running inside Electron.

Notes

This is just a guide to show how this work. However, I don’t recommend use ts-node as a production solution. Also, I have not test the getAppPath function in a bundle application, so it may fail.

Moving forward

We have now a Electron application written in Typescript. It could optimize for production by using a build system, such Webpack. Also, we could target es6 in the tsconfig file as Electron main will work fine with es2015.

Uses of native modules are something that seems to have interest of users, so I’ll probably made a guide about using them.

Series