Static file serving for Electron apps
npm install electron-serve> Static file serving for Electron apps
Normally you would just use win.loadURL('file://…'), but that doesn't work when you're making a single-page web app, which most Electron apps are today, as history.pushState()'ed URLs don't exist on disk. It serves files if they exist, and falls back to index.html if not, which means you can use router modules like react-router, vue-router, etc.
``sh`
npm install electron-serve
Requires Electron 37 or later.
`js
import {app, BrowserWindow} from 'electron';
import serve from 'electron-serve';
const loadURL = serve({directory: 'renderer'});
let mainWindow;
(async () => {
await app.whenReady();
mainWindow = new BrowserWindow();
await loadURL(mainWindow);
// Or optionally with search parameters.
await loadURL(mainWindow, {id: 4, foo: 'bar'});
// The above is equivalent to this:
await mainWindow.loadURL('app://-');
// The - is just the required hostname`
})();
#### options
Type: object
##### directory
Type: string\'.'
Default:
The directory to serve, relative to the app root directory.
##### scheme
Type: string\'app'
Default:
Custom scheme. For example, foo results in your directory being available at foo://-.
##### hostname
Type: string\'-'
Default:
Custom hostname.
##### file
Type: string\'index'
Default:
Custom HTML filename. This gets appended with '.html'.
##### isCorsEnabled
Type: boolean\true
Default:
Whether CORS should be enabled.
Useful for testing purposes.
##### partition
Type: string\electron.session.defaultSession
Default:
The partition where the protocol should be installed, if not using Electron's default partition.
The serve function returns a loadUrl function, which you use to serve your HTML file in that window.
##### window
Required\
Type: BrowserWindow
The window to load the file in.
##### searchParameters
Type: object | URLSearchParams
Key value pairs or an URLSearchParams instance to set as the search parameters.
ES modules (ES2015+ modules) work out of the box. JavaScript files are served with the correct text/javascript MIME type, allowing you to use ES6 import/export syntax:
`html`
Source maps are fully supported for debugging. .map files are served with the correct MIME type, enabling Chrome DevTools to load them properly for debugging minified code.
Since files are served via a custom protocol, Node.js require() calls with relative paths won't work as expected. Use instead of