Skip to content

Instantly share code, notes, and snippets.

@treshugart
Last active April 19, 2019 04:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save treshugart/3dddaa6df8683afaf6bbba917e6ed95e to your computer and use it in GitHub Desktop.
Save treshugart/3dddaa6df8683afaf6bbba917e6ed95e to your computer and use it in GitHub Desktop.
Server-side rendering web components in Electron

To render a component:

electron server.js --html "<x-app></x-app>" --scripts ./entry-point

Where --html is the HTML that you want to render and --scripts is the entry point that will be loaded prior to rendering the HTML. The entry point should contain all your component definitions that you need for the HTML to be rendered.

<!DOCTYPE html>
<html>
<body>
<div id="fixture"></div>
<script>
const fixture = document.getElementById('fixture');
const { ipcRenderer } = require('electron');
ipcRenderer.on('render', (e, data) => {
const { html, scripts } = data;
scripts.forEach(require);
fixture.innerHTML = html;
ipcRenderer.send('render', fixture.innerHTML);
});
</script>
</body>
</html>
const { app, BrowserWindow, ipcMain } = require('electron');
const { html, scripts } = require('minimist')(process.argv);
function ensureArray(arr) {
return Array.isArray(arr) ? arr : [arr];
}
app.on('ready', () => {
const win = new BrowserWindow();
win.loadURL(`file://${__dirname}/server.html`);
win.webContents.on('did-finish-load', () => {
win.webContents.send('render', { html, scripts: ensureArray(scripts) });
});
ipcMain.on('render', function (e, html) {
console.log(html);
});
});
@lastmjs
Copy link

lastmjs commented Aug 15, 2016

Nice! How is this expected to be used in a server-side app? It looks like if I had a Node.js app that I'd have to spin up a child process and execute this on the command line.

@treshugart
Copy link
Author

treshugart commented Aug 28, 2016

@lastmjs Currently you'd have to spin it up in a child process. I didn't think about it much, just exploring. You could build a microservice around it.

@pyrossh
Copy link

pyrossh commented Nov 22, 2016

Is there no way to do this programatically like using phantomjs or an alternate? Coz spinning up a process would defeat the purpose of node's single event loop and would reduce performance overall.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment