Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import my own files into the electron renderer process

Tags:

electron

This seems really dumb, but I need help for importing some source code into the renderer process in electron:

I have an electron app: index.html (loads window.js with a tag) - index.js - window.js - useful_functions.js

In window.js, I want to import some functions from useful_functions.js, so I've tried the following:

// fails with: Uncaught SyntaxError: Unexpected identifier
import { very_useful } from './useful_functions.js';

// fails with: Uncaught ReferenceError: require is not defined
const { very_useful } = require('./useful_functions.js');

// fails with: Uncaught ReferenceError: require is not defined
require('electron').remote.require('./useful_functions.js')

I also tried the nodeIntegration flag, but that didn't help either

Note: I'm not trying to import npm modules but my own code, in an other file right next to it.

I'm looking for examples, but I only find super small samples with just the basic files. (Or huge apps like atom that would take me a while to figure out)

I don't have webpack setup for this project yet, but I'm sure there is a simpler way to do this very basic task...

Thanks for any help.

like image 308
bastien girschig Avatar asked Dec 27 '25 16:12

bastien girschig


1 Answers

In index.html, use require() instead of loading window.js with a tag, i.e., replace:

<script src="window.js"></script>

with:

<script>require('./window.js');</script>

Then, in window.js, the following statement should work too:

const { very_useful } = require('./useful_functions.js');

Note that nodeIntegration: true is needed in the options passed to new BrowserWindow() anyway:

webPreferences:
{
    nodeIntegration: true
}

See:

  • Node Modules

Functions and objects are added to the root of a module by specifying additional properties on the special exports object.

Variables local to the module will be private, because the module is wrapped in a function by Node.js (see module wrapper).

  • Module Wrapper

Before a module's code is executed, Node.js will wrap it with a function wrapper that looks like the following:

(function(exports, require, module, __filename, __dirname) {
// Module code actually lives in here
});

like image 59
Ally Gator Avatar answered Dec 31 '25 17:12

Ally Gator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!