April 25, 2016
Setup Ionic 2 with Electron (TypeScript, Angular2)
Recently i faced the challenge to create a cross platform application for desktop, mobile and browser. Since Angular 2 Material is not yet ready but a Angular 1 to Angular 2 migration would be a pain in the ass I decided to go with Ionic 2 as scaffold for all devices. And then, when Angular 2 Material is ready it should replace Ionic 2 on Desktop and in Browser.
1.) The set up with was surprisingly easy. First of all make sure to have ionic 2 installed.
1 |
ionic -v |
2.) To kickstart the Ionic 2 project. TypeScript is not required, but recommended, although you can do anything shown here with JavaScript as well.
1 |
ionic start ionic2-electron tutorial --v2 --ts |
3.) Browse to your app and install electron.
1 2 |
cd ionic2-electron npm install electron-prebuilt --save-dev |
4.) Now go to your package.json file and add the required scripts for electron to start in dev mode with auto reload and in dist without.
1 2 3 4 5 |
"scripts": { "electron": "electron .", "electron dist": "electron ." }, "main": "electron.js" |
5.) So your full package.json should look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
{ "dependencies": { "angular2": "2.0.0-beta.15", "es6-shim": "^0.35.0", "ionic-angular": "2.0.0-beta.6", "ionic-native": "^1.1.0", "ionicons": "3.0.0-alpha.3", "pouchdb": "^5.3.2", "reflect-metadata": "0.1.2", "rxjs": "5.0.0-beta.2", "zone.js": "^0.6.11" }, "devDependencies": { "del": "2.2.0", "electron-prebuilt": "^0.37.7", "gulp": "3.9.1", "gulp-watch": "4.3.5", "ionic-gulp-browserify-typescript": "^1.0.0", "ionic-gulp-fonts-copy": "^1.0.0", "ionic-gulp-html-copy": "^1.0.0", "ionic-gulp-sass-build": "^1.0.0", "ionic-gulp-scripts-copy": "^1.0.1", "run-sequence": "1.1.5" }, "name": "client", "description": "client: An Ionic project", "cordovaPlugins": [ "cordova-plugin-device", "cordova-plugin-console", "cordova-plugin-whitelist", "cordova-plugin-splashscreen", "cordova-plugin-statusbar", "ionic-plugin-keyboard" ], "cordovaPlatforms": [ "android" ], "scripts": { "electron": "electron .", "electron dist": "electron ." }, "main": "electron.js" } |
6.) Next step is to create the in “main” mentioned electron.js script. This script is basically the setup for your electron app.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
'use strict'; const electron = require('electron'); // Module to control application life. const {app} = electron; // Module to create native browser window. const {BrowserWindow} = electron; let win; function createWindow() { // Create the browser window. win = new BrowserWindow({width: 800, height: 600}); var url = 'http://localhost:8100'; var Args = process.argv.slice(2); Args.forEach(function (val) { if (val === "dist") { url = 'file://' + __dirname + '/www/index.html' } }); // and load the index.html of the app. win.loadURL(url); // Open the DevTools. win.webContents.openDevTools(); // Emitted when the window is closed. win.on('closed', () => { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. win = null; }); } // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.on('ready', createWindow); // Quit when all windows are closed. app.on('window-all-closed', () => { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', () => { // On OS X it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (win === null) { createWindow(); } }); |
7.) Your project structure will now look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
. ├── app ├── config.xml ├── electron.js ├── gulpfile.js ├── hooks ├── ionic.config.js ├── ionic.config.json ├── node_modules ├── package.json ├── platforms ├── plugins ├── resources ├── tsconfig.json ├── typings ├── typings.json └── www |
8.) Thats it! Now you can fire it up:
1 2 3 4 5 6 7 8 |
# start ionic and electron with autoreload, ionic serve # open another terminal window for the npm run command! npm run-script electron # use electron in dist ionic build browser npm run-script electron dist |
Ionic 2 running in Electron
Run Ionic 2 in Electron always in Windows Design
By default Ionic 2 runs in Material Design if no special platform is detected (e.g. when running in browser. But also when running on Linux Electron!). So you might want your electron App to run with Windows Theme on all platforms. The simplest way to do so is to add a Ionic Config Parameter to the URL. They have to be prefixed with “Ionic” and the fist letter is always uppercase. See the given example below of the modified electron.js.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
... function createWindow() { // Create the browser window. win = new BrowserWindow({width: 800, height: 600}); var url = 'http://localhost:8100?ionicMode=wp'; var Args = process.argv.slice(2); Args.forEach(function (val) { if (val === "dist") { url = 'file://' + __dirname + '/www/index.html?ionicMode=wp' } }); // and load the index.html of the app. win.loadURL(url); // Open the DevTools. win.webContents.openDevTools(); // Emitted when the window is closed. win.on('closed', () => { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. win = null; }); } ... |
Hi,
thanks for sharing this example!
I tried to follow your instructions but I’m not able to run “npm run-script electron” successfully. I get the following error: https://postimg.org/image/717cf4hip/
I guess you are not running windows, but maybe you still have an idea what’s going wrong here?
Thanks 🙂
I’m not too familiar with Electron on Windows but why is the error from MS JScript?
What happens when you run “electron” from the commandline? Maybe you need it global
After starting from scratch it is working now, but I have no idea why :/
looks nice. However: (1) using rendererprocess with browserify in ionic app and (2) more horrible using typescript with electron. so so painful 🙁
@Stefan Just use typings (npm i -g tsd)
When running the electron command (by script or directly on the Windows Command Line), it just opens electron.js in notepad++.
Do I need to change the default app for *.js files to something else?
Hello Jürgen,
what command are you firing exactly? npm run electron in the project folder should do open a electron window showing your app.
Hi Can,
i used “electron .” and “npm run-script electron”. T
The issue was with “electron.js”, which overloaded electron.exe on the command line while me being in the app’s main directory. Once I changed it to main.js like in the electron starter example it worked.
So to improve this blog I suggest not mixing up electron binary and JS file names, at least with Windows.
Best regards,
Jürgen
That’s an amazing tutorial that shows how simple electron integrates your project.
Thanks for sharing that!
(I confirm the ‘electron’ file/binary confusing Windows platform).
Christophe K.
Hi. Nice tutorial.
Can you help with the packaging of the app using electron-package or electron-build? I gave it a try but could not come out with a working app. 🙂
Hi Luca,
Did you ever get a response about how to use electron-builder in this example? I’m stuck at this point as well.
Thanks.
Hi Can,
Being absolutely new to both Ionic 2 and Electron I am glad I stumbled upon your tutorial.
Very very helpful and nicely organized, step-by-step tutorial to get up and running with embedding Ionic 2 in Electron.
I am not sure if you are still following up with this blog. Just checking if you have any suggestion for me to get past my issue after following your steps to the ‘T’! 🙂
In my case, “ionic serve” works fine…it opens up the Ionic 2 app in a browser window. But when I run “npm run-script electron” or “electron .” command it is opening up the Electron window for Desktop application but does not render the Ionic app in it. It does show the HTML Title correctly in the title bar of Desktop application window so looks like it’s a problem with rendering the content. Not sure where and what to look for.
Any help will be greatly appreciated!
Hello Gauzy,
have you checked for errors in console of Electron? In order to do so, use Ctrl+Shift+I or F12.
hi can,
it worked fine for me. Thanks a lot! i only had to replace the > String with > in the electron.js
kindly
Olli
Thanks for the good blog.
I have two question:
1. Following to your blog, it look like that if I have exist ionic-2-app, I can also install electron and it will work Did I understand you well?
2. You wrote:
“And then, when Angular 2 Material is ready it should replace Ionic 2 on Desktop and in Browser”.
Is it so necessary?
My customer want me to continue use the same project, and only build new html and css pages, and cause electron to load them whan I on desktop.
I must use Ionic if I want to do that because my logic pages (typescript) are base on Ionic.
Is it possible to ue Ionic-2 for desktop-site also?
Hi,
I am trying to run the application using windows machine.I tried to follow your instructions but I’m not able to run “npm run-script electron” successfully. I get the “Microsoft script compilation Error” from ms script.
Please suggest what will fix this problem.
Hi Sarath,
You should rename ‘electron.js’ to ‘main.js’ or other name
and update ‘package.json’ with new name of ‘main’ property.
Because when we run ‘electron .’, Windows will try to execute the ‘electron.js’…
Hi Guys,
i am new as well to this topic.
Followed the tutorial and at the end there is a JS-error. Tried to rename the electron.js file to main.js, but did not help.
This is the error msg:
Uncaught Exception:
/Users/oliver/Development/IonicProjects/ionic2-electron/main.js:29
win.on(‘closed’, () => {
^^
ReferenceError: Invalid left-hand side in assignment
at Object.exports.runInThisContext (vm.js:78:16)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at loadApplicationPackage (/Users/oliver/Development/IonicProjects/ionic2-electron/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar/main.js:283:12)
at Object. (/Users/oliver/Development/IonicProjects/ionic2-electron/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar/main.js:325:5)
at Object. (/Users/oliver/Development/IonicProjects/ionic2-electron/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar/main.js:361:3)
at Module._compile (module.js:571:32)
It’s hard to tell what the issue is without more context, but you should check the syntax near line 29 of your main.js file… Also, make sure that the thing to the right of the equal sign is a greater-than sign (i.e. =>) and not the HTML code for it (%gt;)
Hello how you doing?!
I would like to say thank you very much for your work and keep sharing the best content, take care!
Greetings from old west
James