Require JavaScript file in Renderer Process


#1

Hello everyone. I’m new to Electron and have a problem in regards to my current project.

I have index.html in the app folder, which is loaded by main.js (main process, located at the project’s root). index.html has a script tag with a source pointing to index.js’s location (js/index.js). What I want to do is require a script located under app/db, which contains an interface for the database.

However, in the index.js file, require() doesn’t work (when trying to point app/db/orders.js).

How can I require() .js files (particularly orders.js) in index.js?

Please ask me for more information if necessary.

Thanks,
Carlos


#2


#3

If you’re using the built-in require function, then it loads by default on relative paths from the file that you’re calling require in. So if you are calling require in app/js/index.js and you want to import app/db/orders.js, then you need to use require('../db/orders').


#4

Sorry for the late response.

Chrome DevTools keeps throwing Uncaught Error: Cannot find module '../db/orders'.

In index.html I’ve tried including the js/index.js file as <script>require("js/index.js");</script> and as <script src="js/index.js"></script>.

js/index.js:

const {db, orders} = require('../db/orders');

db.none(orders.insert)
    .then(function () {
        
    })
    .catch(function (error) {
        console.log(error);
    });

db.any(orders.get)
    .then(function (data) {
        document.body.appendChild(document.createElement("p").textContent = data);
    })
    .catch(function (error) {
        console.log(error);
    });

Thanks,
Carlos


#5

@leedohm forgot the mention.


#6

UPDATE
Just found the solution (albeit I still don’t understand the problem in its entirety).

This is what I modified in js/index.js:

const path = require("path");
const {db, order} = require(path.resolve('app/db/orders'));

Why does the error 'cannot find module' occur in render process
#7

THANK YOU!

The reason is because, in your HTML file, process.cwd() is the root of your application but __dirname is ./node_modules/electron/dist/Electron.app/Contents/Resources/electron.asar/renderer (or something like it).

So using path.resolve(...) gets an absolute path based on process.cwd().


#8

It looks like relying on process.cwd() is unreliable. (It’s different when running with electron . as opposed to a packaged app). But this seems to work for me:

let {remote} = require('electron');
let path = require('path');
let appPath = remote.app.getAppPath();
const { mything } = require(path.resolve(appPath, './path/to/my/thing'));