Search code examples
typescriptelectronimporterror

How to use es6 import for importing electron instead of require function


I am new to electron and making GUIs using node Js. I referred the docs of electron and there they used require statement to import the module. When I tried to import it using an ES6 import I faced an error.

enter image description here

npm version - 6.14.15

node version - v14.17.6

electron version - 16.0.7

package.json file looks something like this -

{
  "name": "typing-speed-tester",
  "version": "1.0.0",
  "description": "This is a typing speed tester which will calculate your typing speed and accuracy of the typed words",
  "main": "index.ts",
  "scripts": {
    "start": "electron ."
  },
  "author": "Gahan",
  "license": "ISC",
  "devDependencies": {
    "electron": "^16.0.7"
  }
}

This is the index.ts file

const { app, BrowserWindow } = require('electron');
const createWindow = () => {
    const Window = new BrowserWindow({
        width: 800, height: 600
    })
    Window.loadFile("index.html")
}

app.whenReady().then(() => {
    createWindow();
})

Here I want to replace the require with the import keyword Thanks in advance for the help


Solution

  • It seems that you are missing a module resolution setting used by Ts compiler.

    You can add a tsconfig.json file in your project root containing a compilerOptions.module value:

    {
        "compilerOptions": {
            "module": "es2015"
        }
    }
    

    See Typescript documentation for further details.