0

I have an electron app that is written in typescript. Here is the minimum code:

someModule.ts:

function someFunction() {}

export default someFunction;

main.ts:

import someFunction from "./someModule";

someFunction();

index.html:

...

<script defer src="main.js"></script>

...

index.ts (package entry which starts with npm start):

import { BrowserWindow, app } from "electron";

const createWindow = () => {
    const win = new BrowserWindow({
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
        }
    });

    win.loadFile("./index.html");
}

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

app.on("window-all-closed", () => {
    if(process.platform !== "darwin") app.quit();
})

tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["DOM"], 
    "module": "CommonJS",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true, 
    "skipLibCheck": true                                 
  }
}

When I run the app (by npx tsc && node index.js command (which is npm start in package scripts)) the console in electron window gives an error:

Uncaught ReferenceError: exports is not defined
    at main.js:5:23

How can I fix this?

4
  • perhaps something to do with your tsconfig.json (see stackoverflow.com/questions/43042889/…) Commented Dec 5, 2022 at 14:27
  • @UsithaIndeewara sorry didn't read your code closely enough. You need to set your module type to commonjs in your tsconfig, and make sure you do not have type: module in your package.json. Electron is node.js, it doesn't support the ESM syntax for .js files. See also this q/a Commented Dec 5, 2022 at 15:05
  • My tsconfig already has "module": "commonjs" and I don't have "type": "module" in package.json. But the error occurs. @JaredSmith @AlainBUFERNE Commented Dec 6, 2022 at 0:56
  • Does this answer your question? Typescript & Electron exports is not defined Commented Apr 3, 2024 at 6:51

1 Answer 1

0

The problem was solved by adding this in the index.html file:

<script>
    require("./main.js");
</script>

instead of <script src="main.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.