Bundling Your Renderer Script
Tldr
We can use Webpack to package the renderer script (and its dependencies) into a bundle that
works in a browser and therefore don't need to turn on nodeIntegration
to enable Node.js require
.
We don't have to disable context isolation either if we simply export a function that we can invoke in the right execution context.
Main Process
main.js
const {app, BrowserWindow} = require('electron');
app.whenReady().then(async () => {
const bwin = new BrowserWindow({
width: 400,
height: 250,
webPreferences: {
nodeIntegration: false, // <- Good!
contextIsolation: true // <- Nice!
}
});
await bwin.loadFile('renderer.html');
bwin.show();
});
Renderer Page
Note that we import the bundle not the original source file.
renderer.html
<html>
<head>
<style>
body {background-color:black;color:limegreen}
</style>
</head>
<body>
<pre></pre>
<script src="./renderer.bundle.js"></script>
<script>
window.app02('pre');
</script>
</body>
</html>
Renderer Script
This code will eventually run in the renderer process but not as is. This module will get bundled by Webpack into a browser-compatible form.
renderer.js
const answer = require('./answer');
module.exports = sel => {
document.querySelector(sel).innerHTML = answer();
};
Webpack Configuration
The bundle exports a function at window.app02
which can be invoked in the renderer page.
webpack.config.js
module.exports = {
mode: 'production',
context: __dirname,
entry: {
renderer: './renderer.js'
},
output: {
path: __dirname,
filename: '[name].bundle.js',
library: {
type: 'window',
name: 'app02'
}
}
};