Using Node and Electron to build Desktop Apps: Difference between revisions

From NSB App Studio
Jump to navigation Jump to search
(14 intermediate revisions by the same user not shown)
Line 17: Line 17:
[https://electronjs.org/ Electron] is framework which allows for the development of desktop GUI applications. Since it's built on Node.js, it already has the ability to run JavaScript code. It also uses Chrome's browser engine to render the UI using regular HTML. Each Electron app includes the V8 Runtime as well as the Chrome browser. Slack, Github Desktop and WhatsApp are examples of apps built using Electron.
[https://electronjs.org/ Electron] is framework which allows for the development of desktop GUI applications. Since it's built on Node.js, it already has the ability to run JavaScript code. It also uses Chrome's browser engine to render the UI using regular HTML. Each Electron app includes the V8 Runtime as well as the Chrome browser. Slack, Github Desktop and WhatsApp are examples of apps built using Electron.


=== How is this compare to PhoneGap? ===
=== How is this compare to VoltBuilder? ===


PhoneGap (Cordova) is used to package apps for iOS and Android. Electron is used to package apps for Windows, MacOS and Linux. It's quite reasonable to have one AppStudio project that you use with both PhoneGap and Electron, letting you build for all 5 platforms.
VoltBuilder (Cordova) is used to package apps for iOS and Android. Electron is used to package apps for Windows, MacOS and Linux. It's quite reasonable to have one AppStudio project that you use with both VoltBuilder and Electron, letting you build for all 5 platforms.


Nodejs/npm modules are similar to PhoneGap Plugins. Since they are operating system specific, PhoneGap Plugins will not work with Electron (and vice versa).
Nodejs/npm modules are similar to VoltBuilder Plugins. Since they are operating system specific, Cordova Plugins will not work with Electron (and vice versa).


== Tutorial: Make an Electron app ==
== Tutorial: Make an Electron app ==
Line 29: Line 29:
In this tutorial, we're going to use a module from npm called [https://github.com/devfacet/weather weather-js] to create an app which gets weather data from weather.service.msn.com. It's very convenient: we don't have to figure out the MSN API to use it.
In this tutorial, we're going to use a module from npm called [https://github.com/devfacet/weather weather-js] to create an app which gets weather data from weather.service.msn.com. It's very convenient: we don't have to figure out the MSN API to use it.


You will have to know how to use the command line (Terminal on MacOS, cmd or Powershell on Windows) and have AppStudio 7.3.0 or later installed.
We recommend using AppStudio 8 (or later) with this tutorial.


=== Set up the project ===
=== Set up the project ===
Line 39: Line 39:
2. Using AppStudio, create a new project called ElectronWeather and save it. (You can also use the ElectronWeather sample with comes with AppStudio by opening it and doing a "Save As" elsewhere, to create a fresh copy. If you do this, several steps below can be skipped - follow the instructions)
2. Using AppStudio, create a new project called ElectronWeather and save it. (You can also use the ElectronWeather sample with comes with AppStudio by opening it and doing a "Save As" elsewhere, to create a fresh copy. If you do this, several steps below can be skipped - follow the instructions)


3. Using a text editor, create a file called package.json in your project folder, with the following code in it. (Skip this step if you're using the sample).
3. Enter "Weather App" into description in Project Properties.
<pre>
{
  "name": "electronweather.appstudio",
  "version": "1.0.0",
  "description": "This is an app about Weather.",
  "main": "electronMain.js",
  "scripts": {
    "start": "electron .",
    "pack": "electron-builder --dir",
    "dist": "electron-builder"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "weather-js": "^2.0.0"
  }
  "devDependencies": {
    "electron": "^7.0.0",
    "electron-builder": "^21.2.0"
  },
  "build": {
    "appId": "ElectronWeather",
    "mac": {
      "category": "your.app.category.type"
    }
  }
}
</pre>
 
4. Drag and drop package.json into the Project Explorer window in AppStudio. This adds the file to the project. (Skip this step if you're using the sample).


[[File:Electron5.png]]
4. In Project Properties, go to the Electron section and open package.json. Modify the "dependancies" line as follows: (Skip this step if you're using the sample).


5. Using a text editor, create a file called electronMain.js in your project folder, with the following code in it. (Skip this step if you're using the sample). For more information on this file, check out [[electronMain.js]].
<pre>
<pre>
const {app, BrowserWindow, Menu} = require('electron');
   "dependencies": {{
const path = require('path');
     "weather-js": "^2.0.0"
const url = require('url');
   }},
 
let mainWindow;
 
function createWindow () {
   mainWindow = new BrowserWindow({
  width: 768,
  height: 1004,
  icon:__dirname+'/img/AppStudio.icns',
  title: 'Electron Weather',
  webPreferences: {nodeIntegration: true},
  })
 
  mainWindow.loadFile('index.html')
 
  mainWindow.webContents.openDevTools()
  mainWindow.on('closed', function () {
     mainWindow = null
  })
}
 
app.on('ready', createWindow)
 
app.on('window-all-closed', function () {
   if (process.platform !== 'darwin') app.quit()
})
 
app.on('activate', function () {
  if (mainWindow === null) createWindow();
})
</pre>
</pre>


6. Drag and drop electronMain.js into the Project Explorer window of AppStudio. In the file's properties, set loadType to 'noload'. (Skip this step if you're using the sample).
This includes the [https://www.npmjs.com/package/weather-js Weather-js] Node library from npm.
 
[[file:Electron1.png]]


7. To add your own icon, follow these steps. (Skip this step if you're using the sample).
5. To add your own icon, follow these steps. (Skip this step if you're using the sample).
* create a folder named build in your project folder.
* Put an png file at least 512x512 in your project directory.
* put a 512x512 png into the build folder. Name it icon.png.
* Set VoltBuilder icon(1024) to that icon in Project Properties.
* Add build to 'extraheaders' in Project Properties.


=== Add the Weather Code ===
=== Add the Weather Code ===
Line 123: Line 59:
1. Add a button to Form1.
1. Add a button to Form1.


2. In the code window for Form1, paste the following code. You'll notice there is a new function called 'require' in the first line. This function is part of Node.js: it loads the module of that name.
2. In the Code Window for Form1, paste the following code. You'll notice there is a new function called 'require' in the first line. This function is part of Node.js: it loads the module of that name.


Since this function is not part of JavaScript, the project will not run in the browser as a normal project would.
Since this function is not part of JavaScript, the project will not run in the browser as a normal project would.
Line 162: Line 98:
</syntaxhighlight>
</syntaxhighlight>
</tabber>
</tabber>
=== Set up the Deploy ===
1. Add this string to extraheaders in Project Properties:
<pre>
<!-- Electron -->
</pre>
2. In your project folder, create a new folder named electron.
3. In AppStudio Preferences, select 'Deploy to a local folder' and set Local Path to "/Users/george/electronweather.appstudio/electron"
[[File:Electron2.png]]
4. Click on Deploy in the Run menu. This will deploy your app to electron/ElectronWeather. It will ask you if you want to visit the project - click no.
5. Open a command line window in electron/ElectronWeather and type
<pre>
npm install
</pre>
This will install all the node files needed to run your project. You won't have to do this step again unless you change the node modules your app uses.


=== Run the App ===
=== Run the App ===


1. Now we're ready to run the app. From the same command line window, enter
Now we're ready to run the app. On the Run menu, choose "Run Desktop App using Electron"
<pre>
npm start
</pre>
 
Here's the output after we click on the button:
 
[[File:Electron3.png]]


'''Some notes'''
'''Some notes'''
* The Chrome Debugger window opens by default. We'll need this if we are going to debug the app.  
* The Chrome Dev Tools window opens by default. We'll need this if we are going to debug the app.  
* To turn off the Chrome Debugger, comment out line 18 in electronMain.js and run again.
* To turn off the Chrome Dev Tools, set "Chrome Dev Tools" to false in Project Properties.
* The "Electron Security Warning" in the console can be ignored.
* The "Electron Security Warning" in the console can be ignored.


Line 204: Line 112:
We now have a running app. The next step is to package it for distribution. We can make regular executables for distribution on MacOS, Windows and Linux. The packaging has to done on a computer running the OS we are targeting: the MacOS version needs to be build on a Mac, etc.
We now have a running app. The next step is to package it for distribution. We can make regular executables for distribution on MacOS, Windows and Linux. The packaging has to done on a computer running the OS we are targeting: the MacOS version needs to be build on a Mac, etc.


There is more documentation on packaging at https://www.electron.build/
There is more documentation on packaging at https://www.electron.build/. You'll need to pay special attention to code signing requirements.
 
On the Run menu, choose "Make Desktop App for Distribution using Electron". If the build fails, look at the log in "About AppStudio" for more information.


==== MacOS ====
When the build is complete, you will find the executable in your project folder, in


From the command line we have open in electron/ElectronWeather, type this:
electron/ElectronWeather/dist/*
<pre>
npm run pack
</pre>
When complete, you'll find the executable here:
electron/ElectronWeather/dist/mac/electronweather.appstudio.app


To make a distributable file, do this:
=== Tips ===
<pre>
npm run dist
</pre>
When complete, you'll find the distributable here:
electron/ElectronWeather/dist/project1.appstudio-1.0.0.dmg


==== Windows ====
==== Setting Electron Runtime Options ====
From the command line we have open in electron/ElectronWeather, type this:
The operation of Electron apps at runtime can be changed by modifying the electronMain.js module. It's in the Electron section of Project Properties.
<pre>
npm run pack
</pre>
When complete, you'll find the executable here:
electron/ElectronWeather/dist/windows/electronweather.appstudio.exe


To make a distributable file, do this:
You can learn more about the options in [[ElectronMain.js]].
<pre>
npm run dist
</pre>
When complete, you'll find the distributable here:
electron/ElectronWeather/dist/project1.appstudio-1.0.0.nsis


=== Tips ===
==== How to tell if you are running Electron at runtime ====
==== How to tell if you are running Electron at runtime ====
<pre>
<pre>
if (typeof(isElectron) !== "undefined") {
if (NSB.electron) {
   // Code placed in here that would on be run if deployed via Electron
   // Code placed in here that would on be run if deployed via Electron
}
}
Line 248: Line 137:


<pre>
<pre>
if (typeof(isElectron) !== "undefined") {
if (NSB.electron) {
   if (process.platform === "win32") {
   if (process.platform === "win32") {
     // Electron Windows
     // Electron Windows
Line 257: Line 146:
}
}
</pre>
</pre>
=== Debugging ===
# Check the AppStudio Log in 'About AppStudio'. It will have more info.
# To reset the Electron environment, simply delete the electron folder in your project. It will be recreated next time you start your app.
# To start your Electron app in a console, open it in the electron folder of your project directory and enter:
<pre>
npm start
</pre>
# To build your Electron distributable in a console, open it in the electron folder of your project directory and enter:
<pre>
npm run pack
npm run dist
</pre>
=== Troubleshooting ===
If your Electron apps are not running, you may have version mismatches in your electron folder. To resolve these, delete the folder (it's in your project directory). Next time you run, AppStudio will recreate it using the latest versions of everything.

Revision as of 15:40, 24 February 2021

Introduction

AppStudio now supports the use of some of the most important new technologies in the web development world.

Node.js is a runtime environment that executes JavaScript code outside the browser. That makes it suitable for writing server side software, which would normally be done in PHP or other languages. It works by having an executable stub which is able to call the V8 JavaScript engine, which powers Chrome.

npm is a repository of code which can be used with Node.js. It's included when you download Node. There is a huge number of packages available - over 750,000 at last count. You can include these packages in your Node project to add functionality. It might be for convenience: there are a lot of libraries which are much easier to include in your project than to write yourself. It might be for functionality: the modules can implement features which would not be available in the browser.

An example of a convenient library would be Lodash which adds hundreds of additional functions to JavaScript. A missing feature library would be fs-extra which allows full access to the file system.

Electron is framework which allows for the development of desktop GUI applications. Since it's built on Node.js, it already has the ability to run JavaScript code. It also uses Chrome's browser engine to render the UI using regular HTML. Each Electron app includes the V8 Runtime as well as the Chrome browser. Slack, Github Desktop and WhatsApp are examples of apps built using Electron.

How is this compare to VoltBuilder?

VoltBuilder (Cordova) is used to package apps for iOS and Android. Electron is used to package apps for Windows, MacOS and Linux. It's quite reasonable to have one AppStudio project that you use with both VoltBuilder and Electron, letting you build for all 5 platforms.

Nodejs/npm modules are similar to VoltBuilder Plugins. Since they are operating system specific, Cordova Plugins will not work with Electron (and vice versa).

Tutorial: Make an Electron app

AppStudio allows you to make normal AppStudio apps (programmed in Javascript or BASIC) into full blown Electron apps. You can distribute these apps as regular executables, able to run on Windows, MacOS and Linux.

In this tutorial, we're going to use a module from npm called weather-js to create an app which gets weather data from weather.service.msn.com. It's very convenient: we don't have to figure out the MSN API to use it.

We recommend using AppStudio 8 (or later) with this tutorial.

Set up the project

1. Download and install Node. (This also installs npm.)

https://nodejs.org/en/download/

2. Using AppStudio, create a new project called ElectronWeather and save it. (You can also use the ElectronWeather sample with comes with AppStudio by opening it and doing a "Save As" elsewhere, to create a fresh copy. If you do this, several steps below can be skipped - follow the instructions)

3. Enter "Weather App" into description in Project Properties.

4. In Project Properties, go to the Electron section and open package.json. Modify the "dependancies" line as follows: (Skip this step if you're using the sample).

  "dependencies": {{
    "weather-js": "^2.0.0"
  }},

This includes the Weather-js Node library from npm.

5. To add your own icon, follow these steps. (Skip this step if you're using the sample).

  • Put an png file at least 512x512 in your project directory.
  • Set VoltBuilder icon(1024) to that icon in Project Properties.

Add the Weather Code

1. Add a button to Form1.

2. In the Code Window for Form1, paste the following code. You'll notice there is a new function called 'require' in the first line. This function is part of Node.js: it loads the module of that name.

Since this function is not part of JavaScript, the project will not run in the browser as a normal project would.

var weather = require("weather-js");

Button1.onclick = function() {
  weather.find({search: "San Francisco, CA", degreeType: "F"}, weatherFindCallback);
};

function weatherFindCallback(err, result) {
  if(err) {
    NSB.MsgBox(err);
  } else {
    NSB.Print(JSON.stringify(result, null, 2));
  }
}

weather = require("weather-js")
 
function Button1_onclick()
  weather.find({search: "San Francisco, CA", degreeType: "F"}, weatherFindCallback)
End function

function weatherFindCallback(err, result)
  If err Then
    MsgBox(err)
  else
    Print JSON.stringify(result, null, 2)
  End if
End function

Run the App

Now we're ready to run the app. On the Run menu, choose "Run Desktop App using Electron"

Some notes

  • The Chrome Dev Tools window opens by default. We'll need this if we are going to debug the app.
  • To turn off the Chrome Dev Tools, set "Chrome Dev Tools" to false in Project Properties.
  • The "Electron Security Warning" in the console can be ignored.

Distributing the App

We now have a running app. The next step is to package it for distribution. We can make regular executables for distribution on MacOS, Windows and Linux. The packaging has to done on a computer running the OS we are targeting: the MacOS version needs to be build on a Mac, etc.

There is more documentation on packaging at https://www.electron.build/. You'll need to pay special attention to code signing requirements.

On the Run menu, choose "Make Desktop App for Distribution using Electron". If the build fails, look at the log in "About AppStudio" for more information.

When the build is complete, you will find the executable in your project folder, in

electron/ElectronWeather/dist/*

Tips

Setting Electron Runtime Options

The operation of Electron apps at runtime can be changed by modifying the electronMain.js module. It's in the Electron section of Project Properties.

You can learn more about the options in ElectronMain.js.

How to tell if you are running Electron at runtime

if (NSB.electron) {
  // Code placed in here that would on be run if deployed via Electron
}

How to tell if you are running Windows or MacOS at runtime

if (NSB.electron) {
  if (process.platform === "win32") {
    // Electron Windows
  }
  if (process.platform === "darwin") {
    // Electron MacOS
  }
}

Debugging

  1. Check the AppStudio Log in 'About AppStudio'. It will have more info.
  2. To reset the Electron environment, simply delete the electron folder in your project. It will be recreated next time you start your app.
  3. To start your Electron app in a console, open it in the electron folder of your project directory and enter:
npm start
  1. To build your Electron distributable in a console, open it in the electron folder of your project directory and enter:
npm run pack
npm run dist

Troubleshooting

If your Electron apps are not running, you may have version mismatches in your electron folder. To resolve these, delete the folder (it's in your project directory). Next time you run, AppStudio will recreate it using the latest versions of everything.