Home > Blockchain >  Using TypeScript in Electron renderer process
Using TypeScript in Electron renderer process

Time:02-21

I have recently had some struggles with using TypeScript efficiently in my Electron projects. I desire to be able to use TypeScript in both the main process and renderer process with the support for a types.ts file as well.

The only solution I have found as far is using Webpack's TypeScript support with a configuration similar to the following:

const path = require("path");

module.exports = {
  mode: "development",

  // All electron pages with a source file must be added here
  entry: {
    page1: "./src/app/pages/page1/index.ts",
    page2: "./src/app/pages/page2/index.ts",
    page3: "./src/app/pages/page3/index.ts",
  },
  
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.ts', '.js'],
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, './src/app/build'),
  },
};

Using this however feels a bit hacky to me and significantly slows down my workflow due to me having to run Webpack every time I make changes to the project.

I would like to know, is there a better way of doing this? Thanks in advance.

CodePudding user response:

It looks like you could benefit from automatic compilation and reload to speed up your development process. You may have a look at electron-quick-start-typescript, which compiles TypeScript using tsc directly. If you don't need Webpack for reasons other than compiling TypeScript, this approach might work well for you.

Automatic compilation

Using npm run watch (which calls tsc -w) in a separate terminal, TypeScript files are automatically compiled when file changes are detected. You can configure the compilation in tsconfig.json.

Automatic reload of Electron app

The module electron-reload detects changed scripts and reloads the BrowserWindows. If the main process script is changed, it restarts the Electron app as a whole.

npm install electron-reload

Add this to your main process script:

const electronReload = require('electron-reload')(__dirname, {
  electron: path.join(__dirname, '..', 'node_modules', 'electron', 'dist', 'electron'),
  electronArgv: ['dist/main.js']
});
  • Related