A problem with import in TypeScript/Electron.js

Viewed 3123

I have a file index.ts:

import { app, BrowserWindow } from 'electron'
let win

app.on('ready', () => {
  win = new BrowserWindow({
    minHeight: 640,
    minWidth: 480,
    frame:false
  })
  win.loadFile('index.html')
})

If I try to run with: npm start, I got an error:

import { app, BrowserWindow } from 'electron'
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1051:16)
    at Module._compile (internal/modules/cjs/loader.js:1101:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1166:10)
    at Module.load (internal/modules/cjs/loader.js:981:32)
    at Module._load (internal/modules/cjs/loader.js:881:14)
    at Function.Module._load (electron/js2c/asar.js:769:28)
    at loadApplicationPackage (D:\VS Projects\Electron App\node_modules\electron\dist\resources\default_app.asar\main.js:109:16)
    at Object.<anonymous> (D:\VS Projects\Electron App\node_modules\electron\dist\resources\default_app.asar\main.js:155:9)
    at Module._compile (internal/modules/cjs/loader.js:1145:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1166:10)

My package.json:

{
  "name": "electron-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.ts",
  "dependencies": {
    "electron": "^10.1.2"
  },
  "devDependencies": {},
  "scripts": {
    "start": "electron .",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "type": "module"
}

How I can solve it?

2 Answers

Electron runs through node.js and node.js is behind and uses commonjs import syntax.

To import we do:

const {app} = require("electron");

// equivalent to
//import {app} from 'electron' <- don't use in electron

to export we do:

module.exports = app;

// equivalent to
//export default app; <- don't use in electron

It looks like you are trying to use TypeScript with Electron. Electron has types available, however it doesn't directly support executing TypeScript right out of the box. You will need to perform some additional steps to get things working. This goes a bit out of scope of an answer, and would need to be more of a tutorial or example, so I'll provide you with an example from GitHub.

You can view an example of getting started with TypeScript and Electron Here.

Related