Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@lastmjs 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

This comment has been minimized.

Copy link
Owner Author

@treshugart 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.

@pyros2097

This comment has been minimized.

Copy link

@pyros2097 pyros2097 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
You can’t perform that action at this time.