DEV Community

Tomasz Wegrzanowski
Tomasz Wegrzanowski

Posted on

Electron Adventures: Episode 72: NW.js

When I started this series I mentioned that I also want to explore some alternatives to Electron, but so far I didn't.

Let's try one now - NW.js.

It's very similar idea to Electron - it's node + packaged chromium. It's just organized a bit differently, without clear divide between frontend and backend.

You need SDK version

The first problem I found, and that's not explained in any way whatsoever by the website, is that you absolutely need to install -sdk version.

If you install the regular version, trying to open dev tools will crash your app. I'm not sure if it's a bug and it was supposed to ignore this command, or actual security feature. Either way, it's impossible to develop anything this way.

The website says nothing about it, and it strongly implies that you need to compile your own sdk version from source. Fortunately that's not actually necessary.

package.json

So this is the package.json we need. Notice hardcoded -sdk version. Just npm install and we'll go on from here.

{
  "name": "nwjs-app",
  "main": "index.html",
  "scripts": {
    "start": "nw"
  },
  "devDependencies": {
    "nw": "0.57.0-sdk"
  }
}
Enter fullscreen mode Exit fullscreen mode

Entry point

NW.js supports either JavaScript entrypoint like Electron, or HTML entrypoint. As we already did the JavaScript one so many times, let's try the HTML one with "main": "index.html" in package.json.

It's also possible to adjust the parameters of that window like size by tweaking with window properties in the package.json, but we're fine with the defaults.

index.html

Nothing special here, we just load CSS and JS.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="app.css">
  </head>
  <body>
    <header>Hello, World!</header>
    <ul></ul>
    <script src="app.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

app.css

Just some stardard Dark Mode starter:

body {
  margin: 0;
  background-color: #333;
  color: #fff;
}

header {
  text-align: center;
  font-size: 400%;
  font-family: monospace;
}
Enter fullscreen mode Exit fullscreen mode

app.js

nw.Window.get().showDevTools();

let ul = document.querySelector("ul")

for (let k in process.versions) {
  let li = document.createElement("li")
  li.append(`${k} = ${process.versions[k]}`)
  ul.append(li)
}
Enter fullscreen mode Exit fullscreen mode

This does two things. The first is open DevTools. Unlike Electron, these are opened in a separate window. This step crashed the app before I figured out I need to use -sdk version.

The second thing is printing some process.versions data in the document.

Results

Here's the results:

Episode 72 Screenshot

Now that we have NW.js setup, in the next episode we'll try to write some app with it.

As usual, all the code for the episode is here.

Discussion (0)