Preload JS library with Electron and make available in renderer

47 Views Asked by At

I'm upgrading an older ElectronJS app that loads JS libraries in index.html as such:

<script>let ClipboardJS = require('clipboard');</script>

However, this is the obsolete way.

I set up preload.js as follows:

const {
    ipcRenderer,
    contextBridge
} = require("electron");

const clipboardJS = require('clipboard');

contextBridge.exposeInMainWorld('jslibs', {
    clipboardJS: clipboardJS
});

My main.js file contains the following for the BrowserWindow:

// Create the browser window.
win = new BrowserWindow({
    width: 1024,
    height: 768,
    webPreferences: {
        sandbox: false,
        contextIsolation: true,
        preload: path.join(__dirname, "preload.js") // use a preload script
    },
    autoHideMenuBar: true,
    icon: __dirname + '/icons/icon.icns'
});

I initialize a new ClipboardJS this way in my renderer.js:

var clipboard = new jslibs.clipboardJS('.button-clipboard');

The console shows the following error:

Uncaught Error: Cannot call a class as a function

What is the proper way to load JS libraries managed with package.json?

0

There are 0 best solutions below