An easy-to-use cross platform menu for Electron
If you develop desktop applications with Electron, you will quickly need an application menu. Even if you don’t have any menu options that are specific to your application, you will still want to add a menu to get things like copy and paste to work on a mac. Usually you’ll just copy and paste the default example and call it a day. But if you want a menu that has platform-appropriate naming and functionality as well as custom options, you’re in for a bunch of if-clauses and having to maintain multiple menu templates. I created Electron-create-menu to help with this.
Electron-create-menu replaces the Menu api that Electron provides and streamlines the menu creation process by doing a couple of things:
- A platform-appropriate default menu
- Filter out menu items depending on your platform
- Gives an easy hook for i18n translations
- Provides a function to create a separator
How to use
Running it is as simple as importing Menu from electron-create-menu and then calling it in Electron’s app.ready()
:
import Menu from 'electron-create-menu';
/* app setup here */
app.on('ready', () => {
Menu();
});
This gives you a default menu that has all the basics for the current platform covered:
From there on, you can use the callback
to add menu items to the provided default menu:
Menu((defaultMenu, separator) => {
defaultMenu.push({
label: 'My custom menu!',
submenu: [
{label: 'my first item'},
separator(),
{label: 'my second item'},
],
});
return defaultMenu;
});
You don’t have to return defaultMenu, it’s just provided as a convenience. You can also build your own menu from scratch and return that, it’ll also work.
Multiplatform
Each item in the menu can be given two additional properties: hideOn
and showOn
. These accept a string, or an array of strings, that correspond to process.platform
values such as darwin
for MacOs or win32
for Windows. The properties will hide or show the menu item on the corresponding platform. This lets you create platform specific menus without having to maintain multiple templates or push values in with additional if-clauses. It makes your menu more readable and maintainable.
Get it!
There’s a couple more features (such as i18n support for your preferred i18n library) but you can read all of them in the full documentation which is up on npm/electron-create-menu and you can file any feature requests, issues or pull requests over on Github/kilian/electron-create-menu.