#How can I import files to preload.ts

10 messages · Page 1 of 1 (latest)

woven iron
#

So I have 3 scripts + my html file.
main.ts
which basically enables preload.ts, creates the windows etc. Just the basics.

config.ts
Where I simply just export 1 variable:

export let myValue = "123"

Then preload.ts which replaces an element in the html after it is finished loading with myValue imported from config.ts:

import { myValue } from "./config";
window.addEventListener('DOMContentLoaded', () => {
    let h1 = document.getElementById("h1");
    if (h1 != null) {
        h1.innerHTML = myValue;
    }
});

However running this project gives an error saying that it cannot load the config script.

I can easily import and export to the main file, but not to the preload file. How does someone import/export variables in Electron?

#

Btw, I can perfectly run preload.ts if I don't try importing stuff and set h1.innerHTML = stringThatICreateHere.

gloomy falcon
#

Hmm I could be wrong but from my understanding the best way to approach would be with the IPC module.

#

You could try adding a listener to your window for ‘did-finish-load’ and send an ipc message to it with whatever data you need.

#

Best approach if using a preloader would be to only expose certain methods of the IPC module if security is something that concerns your app of course.

#

contextBridge.exposeInMainWorld(
    "api", {
        //send: (channel, data) => {
        request: (channel, data) => {
            // whitelist channels
            let validChannels = ["toMain"];
            if (validChannels.includes(channel)) {
                ipcRenderer.send(channel, data);
            }
        },
        //receive: (channel, func) => {
        response: (channel, func) => {
            let validChannels = ["fromMain"];
            if (validChannels.includes(channel)) {
                // Deliberately strip event as it includes `sender` 
                ipcRenderer.on(channel, (event, ...args) => func(...args));
            }
        }
    }
);
near ledge
#

Try using require instead of import, it should work just fine

#
const {myValue} = require('./config')
woven iron
gloomy falcon
#

No problem