After following the Electron typescript quick-start code structure by cloning the repo, everything worked fine. However, when attempting to split my code into multiple .ts files and import them into the renderer script, I encountered an issue. Upon adding
import { stuff } from "./otherfile.ts"
at the top of renderer.ts, I received an error message stating Uncaught ReferenceError: exports is not defined
.
Further investigation revealed that the problem stemmed from the
"module": "commonjs"
setting in tsconfig. Changing this to esnext
caused Electron to no longer load the preload script.
Has anyone successfully managed to make Electron and typescript work seamlessly, allowing for the use of import statements across multiple files?
Minimal reproducible example:
File structure:
/dist
/dist/main.js
/dist/preload.js
/dist/renderer.js
/dist/stuff.js
/src
/src/main.ts
/src/preload.ts
/src/renderer.ts
/src/stuff.ts
/index.html
/src/main.ts:
import { ipcMain } from "electron"; // Imports work fine in main
...
ipcMain.on(...
/src/preload.ts:
import { contextBridge, ipcRenderer} from "electron"; // Imports work fine in preload
contextBridge.exposeInMainWorld("my-api", { ....
/src/renderer.ts
import stuff from "./stuff.ts"; // Import fails in renderer (exports is not defined error)
/src/stuff.ts
const stuff = { ... };
export default stuff;
/index.html
<html>
...
<script src="./dist/renderer.js"></script>
</html>
ts.config:
- If I change "module" to "es6", then preload.ts will not load.
- If I leave "module" as "commonjs", then imports in renderer.ts do not work.
If I manually add var exports = {}
in renderer.js
after the TS compilation, I encounter a different error stating, "require is not defined".