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.
$ npm install electron-serve
Requires Electron 8 or later.
const {app, BrowserWindow} = require('electron');
const serve = require('electron-serve');
const loadURL = serve({directory: 'renderer'});
let mainWindow;
(async () => {
await app.whenReady();
mainWindow = new BrowserWindow();
await loadURL(mainWindow);
// The above is equivalent to this:
await mainWindow.loadURL('app://-');
// The `-` is just the required hostname
})();
Type: object
Required
Type: string
The directory to serve, relative to the app root directory.
Type: string
Default: 'app'
Custom scheme. For example, foo
results in your directory
being available at foo://-
.
Type: boolean
Default: true
Whether CORS should be enabled. Useful for testing purposes.
Type: string
Default: electron.session.defaultSession
The partition the protocol should be installed to, if you're not using Electron's default partition.
- electron-util - Useful utilities for developing Electron apps and modules
- electron-reloader - Simple auto-reloading for Electron apps during development
- electron-debug - Adds useful debug features to your Electron app
- electron-context-menu - Context menu for your Electron app
- electron-dl - Simplified file downloads for your Electron app
- electron-unhandled - Catch unhandled errors and promise rejections in your Electron app