Search code examples
javascriptnode.jselectroncommonjssvelte

Can't require node modules in JS files in svelte electron


I'm using electron with svelte as my frontend framework.

I have JS files that contain functions used by my svelte components.

When I try to import a node module using require - it returns an empty object. When I use require inside a svelte component it works fine. (I've set nodeIntegration: true in my electron.js file).

How could I fix this?

EDIT: An example:

<!--SvelteComponent.svelte-->
<script>
  import {func} from "./jsFile";
</script>
//jsFile.js
const fs = require("fs"); // This require returns an empty object
export function func {...}

I also get a Rollup warning: (!) Plugin node-resolve: preferring built-in module 'fs' over local alternative at 'fs', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning


Solution

  • It turns out I should have used window.require instead of require