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

Viewed 4720

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

2 Answers

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

Here's a fragment of a working svelte component from my application. All imported or required objects just work fine.

<script>
    import '../../../node_modules/materialize-css/dist/css/materialize.css';
    import '../../../css/material-icons-svelte.css';  // we'd have to adjust the font paths!! check extra.css
    import '../../../node_modules/codemirror/lib/codemirror.css';
    import '../../../node_modules/materialize-css/dist/js/materialize.js';

    const {getState, getStore} = require('../../../dist/store/store.renderer');
    const {ipcRenderer} = require('electron');
    const _ = require('lodash');

Edit

I added this to my App.svelte component, that I use on a svelte app with electron and, well, it works. Prints the fs object to the console and it's not empty

    const fs = require('fs')
    console.log(fs);

nodeIntegration is set to true, this my index.html:

<!doctype html>
<html>
<head>
    <meta charset='utf8'>
    <meta name='viewport' content='width=device-width'>

    <link rel='stylesheet' href='../../../css/global.css'>
    <link rel='stylesheet' href='../../../dist/app/myapp/extra.css'>
    <link rel='stylesheet' href='../../../dist/app/myapp/bundle.css'>
</head>

<body class="grey lighten-4">
    <script src='../../../dist/app/myapp/bundle.js'></script>
</body>
</html>

And I'm on electron 8.2.5

Related