Cross-platform Desktop Application Development: Electron, Node, NW.js, and React - Dmitry Sheiko - E-Book

Cross-platform Desktop Application Development: Electron, Node, NW.js, and React E-Book

Dmitry Sheiko

0,0
41,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Build powerful cross-platform desktop applications with web technologies such as Node, NW.JS, Electron, and React

About This Book

  • Build different cross-platform HTML5 desktop applications right from planning, designing, and deployment to enhancement, testing, and delivery
  • Forget the pain of cross-platform compatibility and build efficient apps that can be easily deployed on different platforms.
  • Build simple to advanced HTML5 desktop apps, by integrating them with other popular frameworks and libraries such as Electron, Node.JS, Nw.js, React, Redux, and TypeScript

Who This Book Is For

This book has been written for developers interested in creating desktop applications with HTML5. The first part requires essential web-master skills (HTML, CSS, and JavaScript). The second demands minimal experience with React. And finally for the third it would be helpful to have a basic knowledge of React, Redux, and TypeScript.

What You Will Learn

  • Plan, design, and develop different cross-platform desktop apps
  • Application architecture with React and local state
  • Application architecture with React and Redux store
  • Code design with TypeScript interfaces and specialized types
  • CSS and component libraries such as Photonkit, Material UI, and React MDL
  • HTML5 APIs such as desktop notifications, WebSockets, WebRTC, and others
  • Desktop environment integration APIs of NW.js and Electron
  • Package and distribute for NW.JS and Electron

In Detail

Building and maintaining cross-platform desktop applications with native languages isn't a trivial task. Since it's hard to simulate on a foreign platform, packaging and distribution can be quite platform-specific and testing cross-platform apps is pretty complicated.In such scenarios, web technologies such as HTML5 and JavaScript can be your lifesaver. HTML5 desktop applications can be distributed across different platforms (Window, MacOS, and Linux) without any modifications to the code.

The book starts with a walk-through on building a simple file explorer from scratch powered by NW.JS. So you will practice the most exciting features of bleeding edge CSS and JavaScript. In addition you will learn to use the desktop environment integration API, source code protection, packaging, and auto-updating with NW.JS.

As the second application you will build a chat-system example implemented with Electron and React. While developing the chat app, you will get Photonkit. Next, you will create a screen capturer with NW.JS, React, and Redux.

Finally, you will examine an RSS-reader built with TypeScript, React, Redux, and Electron. Generic UI components will be reused from the React MDL library. By the end of the book, you will have built four desktop apps. You will have covered everything from planning, designing, and development to the enhancement, testing, and delivery of these apps.

Style and approach

Filled with real world examples, this book teaches you to build cross-platform desktop apps right from scratch using a step-by-step approach.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 260

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Cross-platform Desktop Application Development-Electron, Node, NW.js, and React

 

 

 

 

 

 

 

Build desktop applications with web technologies

 

 

 

 

 

 

 

Dmitry Sheiko

 

 

 

BIRMINGHAM - MUMBAI

< html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

Cross-platform Desktop Application Development-Electron, Node, NW.js, and React

Copyright © 2017 Packt Publishing

 

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

 

First published: July 2017

 

Production reference: 1260717

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-78829-569-7

www.packtpub.com

Credits

Author

 

Dmitry Sheiko

Copy Editors

Dhanya Baburaj

Shaila Kusanale

Akshata Lobo

Reviewer

 

Dobrin Ganev

Project Coordinator

 

Devanshi Doshi

Commissioning Editor

 

Smeet Thakkar

Proofreader

 

Safis Editing

Acquisition Editor

 

Shweta Pant

Indexer

 

Mariammal Chettiyar

Content Development Editor

 

Roshan Kumar

Graphics

 

Jason Monteiro

Technical Editor

 

Akhil Nair

Production Coordinator

 

Shraddha Falebhai

About the Author

Dmitry Sheiko is a web developer, blogger, and open source contributor, living and working in the lovely city of Frankfurt am Main, Germany. Dmitry got hooked on computer programming in late 80s. Since 1998, he has been in web-development. Over the last few years, Dmitry has been creating desktop applications with NW.js/Electron. The very first solutions were made with JavaScript/Backbone, but then he switched to TypeScript/React/Redux.

Dmitry has authored dozens of projects at GitHub, including: nw-autoupdater, Pragmatic CSS, and a CommonJS compiler.

First, I would like to thank my family for their continuous support and for allowing me to realize my own potential. A special thanks to my father who first took me to an industrial computer center when I was about 3 years old. In a decade, with the advance of PCs, I realized that computers mean games and after a while, became curious enough about how the games were built to start learning programming. Thanks to Crytek for giving me the opportunity to pursue my passion for research and development.

About the Reviewer

Dobrin Ganev is a Calgary-based software developer with years of experience in various domains, from large-scale distributed applications to frontend web development with the latest JavaScript frameworks. In recent years, he has been focusing on architecting and prototyping solutions in various subjects, such as enterprise search, GIS, predictive analytics, and real-time distributed systems.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.comand as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

 

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1788295692.

If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

This book is gratefully dedicated to my beloved wife Olga and son Jan. My dears, you were both so supportive and patient throughout my time of writing. You helped me bring this book to life..

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Conventions

Reader feedback

Customer support

Downloading the example code

Downloading the color images of this book

Errata

Piracy

Questions

Creating a File Explorer with NW.js-Planning, Designing, and Development

The application blueprint

Setting up an NW.js project

Node Package Manager

An HTML prototype

Maintainable CSS

Defining base rules

Defining layouts

Defining CSS variables

Sticking the title bar and header

Styling the title bar

Styling the directory list

Styling a file list

Styling the footer

Fulfilling the functional requirements

Starting with ES2015

Scoping

Classes

The template literal

Getters and setters

Arrow functions

Destructuring

Handling windowing actions

Writing a service to navigate through directories

Unit-testing a service

Writing view modules

The DirList module

Unit-testing a view module

The FileList module

The title bar path module

Summary

Creating a File Explorer with NW.js – Enhancement and Delivery

Internationalization and localization

Date format by country

Multilingual support

Context menu

System clipboard

Transferring text

Transferring graphics

Receiving text and graphics

Menu in the system tray

Command-line options

Native look and feel

Source code protection

Packaging

Autoupdate

Summary

Creating a Chat System with Electron and React – Planning, Designing, and Development

Application blueprint

Electron

React

Electron meets React

Enabling DevTools extensions

Static prototype

Summary

Creating a Chat System with Electron and React – Enhancement, Testing, and Delivery

Revitalizing the title bar

Utilizing WebSockets

Implementing chat services

Bringing functionality to the components

Writing unit-tests

Packaging and distribution

Deployment and updates

Summary

Creating a Screen Capturer with NW.js, React, and Redux – Planning, Design, and Development

Application blueprint

Setting up the development environment

Static prototype

Comprehending redux

Introducing the application state

Summary

Creating a Screen Capturer with NW.js: Enhancement, Tooling, and Testing

Tooling Redux

Redux DevTools

Unit-testing Redux

Testing action creator

Testing reducers

Taking a screenshot

Recording a screencast

Taking advantage of the system tray

Registering global keyboard shortcuts

Summary

Creating RSS Aggregator with Electron, TypeScript , React, and Redux: Planning, Design, and Development

Application blueprint

Welcome to TypeScript

Setting up the development environment for TypeScript

Basic types

Array, plain objects, and indexable types

Function type

Class type

Abstract classes

Enum type

Union and intersection types

Generic type

Global libraries

Creating static prototype

Setting up the development environment for the application

React-MDL

Creating the index.html

Creating the container component

Creating the TitleBar component

Creating the Menu component

Creating the feed component

Adding custom styles with SASS

Summary

Creating RSS Aggregator with Electron, TypeScript, React, and Redux: Development

Creating a service to fetch RSS

Creating a service to manage feed menu

Actions and Reducers

Connecting to the store

Consuming store from the components

Creating router service

Summary

Preface

HTML5 desktop application development is gaining momentum, and it s no wonder if you take into consideration that JavaScript is now the most popular programming language on the web. The set of HTML5 features combined with Node.js and the runtime API is impressively rich, to say nothing of the countless Node.js modules available on GitHub. In addition, HTML5 desktop applications can be distributed across different platforms (Window, macOS, and Linux) without any modifications in the code.

The goal of this book is to help the reader discover what exciting opportunities unlock Node.js-driven runtime (NW.js and Electron) to a JavaScript developer and how surprisingly easy it is to catch up on programming specifics in this area.

 

What this book covers

Chapter 1, Creating a File Explorer with NW.js - Planning, Designing, and Development, shows that development starts with the blueprint of the file explorer application. We set up a development environment for NW.js and get a crash course on npm, which we will use to install any additional software, and build and run applications. We develop a static prototype of the application. On the way, we learn the best practices for writing maintainable CSS and get a brief introduction to ES2015.

Chapter 2, Creating a File Explorer with NW.js - Enhancement and Delivery, covers the extension and finalization of the application. For that, we master desktop environment integration APIs such as the clipboard, context menu, and tray. We provide file explorer with support for multiple languages and locales. We make it respond to command-line options. We examine pre-production aspects such as code protection, packaging, and autoupdate.

Chapter 3, Creating a Chat System with Electron and React - Planning, Designing, and Development, teaches us how to develop a chat system with Electron and React so, we get an introduction to both of them. We configure the Webpack bundler to transpile React components with JSX syntax. In addition, we make it process CSS files requested as modules. Thus, we can load the assets of the Electron-dedicated library Photonkit. We add the DevTool React extension in Electron and come up with a static prototype at the end of the chapter.

Chapter 4, Creating a Chat System with Electron and React - Enhancement, Testing, and Delivery, covers bringing the application to life. We use the Electron API and React state to implement windowing functions. We learn to use the WebSocket API to provide the chat with bidirectional communication. We examine the unit testing of views and services, and explore Electron-specific packaging, distribution, and autoupdates.

Chapter 5, Creating a Screen Capturer with NW.js, React, and Redux - Planning, Design, and Development, explains how to build a screen capturer based on global application state driven by Redux. In development, we use ready-made React components from the Material UI library. At the end of the chapter, we have a static prototype.

Chapter 6, Creating a Screen Capturer with NW.js - Enhancement, Tooling, and Testing, outlines how to make the application take screenshots and record screencasts. We learn to use WebRTC APIs to get the video stream. We make it generate a still frame image for screenshots and capture the video stream in a file for screencasts. We use the Notification API to inform the user about actions performed, regardless of what window is in focus. We make capturing actions available via global keyboard shortcuts.

Chapter 7, Creating RSS Aggregator with Electron, TypeScript , React, and Redux - Planning, Design, and Development, prepares us to develop a RSS aggregator. For that application, we take advantage of static typing with TypeScript and so, learn the essentials of programming languages. We build a static prototype with the React components of the React MDL library.

Chapter 8, Creating RSS Aggregator with Electron, TypeScript, React, and Redux - Development, explores how to develop the application. On the way, we will learn to use asynchronous actions, and access the store from React components and from services. We will also examine the peculiarities of rendering guest content in Electron.

What you need for this book

To build and run the examples in this book, you need either Linux or macOS; you will also need npm/Node.js. At the time of writing, the author tested the examples with the following software:

npm v.5.2.0

node v.8.1.1

Ubuntu 16.04 LTS, Windows 10, and macOS Sierra 10.12

Who this book is for

This book has been written for any developers interested in creating desktop applications with HTML5. The first two chapters require essential web-master skills (HTML, CSS, and JavaScript) and the basics of Node.js. This part of the book includes a crash course on npm, which will be used across the book to build and run examples, given that you have experience with the command line in your OS (Linux, macOS, or Windows). The next four chapters welcome a minimal experience with React. And finally, for the last two chapters, it would be helpful to have a basic knowledge of TypeScript.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Well, we can change the locale and trigger the event. What about consuming modules? In the FileList view, we have the formatTime static method that formats the passed-in timeString for printing. We can make format it in accordance with the currently chosen locale."

A block of code is set as follows:

{ "name": "file-explorer", "version": "1.0.0", "description": "", "main": "main.js", "scripts": { "test": "echo "Error: no test specified" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }

Any command-line input or output is written as follows:

sudo

npm install nw --global

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "The menu Show Item contains Folder, Copy, Paste, and Delete."

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book--what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

 

Choose from the drop-down menu where you purchased this book from.

Click on

Code Download

.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for Windows

Zipeg / iZip / UnRarX for Mac

7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Cross-platform-Desktop-Application-Development-Electron-Node-NW.js-and-React. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/CrossplatformDesktopApplicationDevelopmentElectronNodeNWJSandReact_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Creating a File Explorer with NW.js-Planning, Designing, and Development

Nowadays, when speaking of HTML5 desktop application development, one implies either NW.js or Electron. The first one has a shorter learning curve, which makes it a better choice for the beginning. Our first application will be a File Explorer. This sort of software is traditionally considered as a classical desktop application. I believe that you will find it exciting to build a File Explorer with HTML, CSS, and JavaScript. This chapter requires no skills in JavaScript frameworks, as we will use none. All you need is a basic knowledge of HTML, CSS, and plain JavaScript (including Node.js).

So, what are we up to? We will plan and sketch the project. We will set up the development environment and create a static prototype and run it with NW.js. We will implement the basic functionality, making it ready to be enhanced in Chapter 2, Creating a File Explorer with NW.js Enhancement and Delivery.

The application blueprint

By File Explorer, I mean a small program that allows navigating through the filesystem and performs basic operations on the files, which can be expressed with the following user stories:

As a user, I can see the content of the current directory

As a user, I can navigate through the filesystem

As a user, I can open a file in the default associated program

As a user, I can delete a file

As a user, I can copy a file in the clipboard and paste it later in a new location

As a user, I can open the folder containing the file with the system file manager

As a user, I can close the application window

As a user, I can minimize the application window

As a user, I can maximize and restore the application window

As a user, I can change the application language

It would be easier to perceive it in a visual form, wouldn't it? Wireframes come in handy here. Wireframe is a skeletal framework of the application that depicts the arrangement of the application's content, including UI elements and navigation system. Wireframe has no real graphics, typography, or even colors. It shows schematically, what the application does. As you know, drawing with a pencil on a paper is possible, but it is not the best way to create a wireframe; what we need is a prototyping tool. Today, there are plenty of solutions on the market. Here, I use an impressive, but affordable tool called WireframeSketcher (http://wireframesketcher.com/). It allows you to sketch web, desktop, and mobile applications (just what we need). It also has a rich mock-up gallery of stencils, widgets, icons, and templates that makes prototyping fast and easy. Besides, the wireframes look nice in a sketchy style:

What we can see on the wireframe is often called a Holy Grail Layout. In our case, the header serves as the window title bar. There, we keep our controls for window actions such as close, maximize, and minimize. Besides that, in the title bar, we display the path to the current directory. In the sidebar, we have our filesystem navigation. The main section contains a table that represents files of the current directory. It has columns--Name, Size, and Modified. A right-click on a file opens a context menu with available file operations. The footer comprises the application title and a language selector combo box.

Setting up an NW.js project

NW.js is an open source framework for building HTML, CSS, and JavaScript applications. You can also see it as a headless browser (based on Chromium https://www.chromium.org/) that includes Node.js runtime and provides desktop environment integration API. Actually, the framework is very easy to start with. What we need is just a start page HTML file and project manifest file (package.json).

To see it in action, we will create a project folder named file-explorer at an arbitrary location. The choice of the folder location is up to you, but I personally prefer to keep web projects in /<username>/Sites on Linux/macOS and %USERPROFILE%Sites on Windows.

As we enter the directory, we create placeholder folders for JavaScript and CSS sources (js and assets/css):

We also place a start page HTML (index.html) that consists of just a few lines:

./index.html<!DOCTYPE html><html> <body> <h1>File Explorer</h1> </body></html>

As you can guess, we shall see just this text--File Explorer-- when feeding this file to a browser.

Now, we need the Node.js manifest file (package.json). Node.js, embedded in the framework, will use it to resolve dependency package names when called with a require function or from an npm script. In addition, NW.js takes from it the project configuration data.

Why not create the manifest file and populate it with dependencies using the npm tool?

Node Package Manager

Nowadays, Node Package Manager (npm) is one of the most demanded gadgets in the web developer tool belt. It's a command-line utility connected with the corresponding online repository of packages and is capable of package installation, version management, and dependency management. So, when we need a package (library, framework, and module), we will check whether it's available in the npm repository and run npm to bring it into our project. It not only downloads the package, it also resolves its dependencies and does it pretty smartly. Furthermore, npm is pretty handy as an automation tool. We can set various command-line tasks to refer any of the locally installed packages by name. The npm tool will find the executable package among installed packages and run it.

The npm tool is distributed together with Node.js. So, you can find an installer for Windows or for macOS on the Node.js download page (https://nodejs.org/en/download). It is also available as an APT package, so you can install it for Linux with the apt-get tools:

sudo apt-get install npm

If you have already installed npm, ensure that it's up to date:

sudo

npm install npm@latest -g

As I have already said, we can install packages with npm-- for example, NW.js. If we want to do it globally, we will run the following command:

sudo

npm install nw --global

Alternatively, we can run the following command:

sudo

npm i nw -g

This will download the latest build of NW.js in {prefix}/lib/node_modules/ and place the executable file in {prefix}/bin. It adds the binary to the PATH environment variable, so one can call nw in any location in the shell.

{prefix} In order to find out what {prefix} is one can run:npm config get prefix. On Linux/macOS it will be /usr/local. On Windows %APPDATA%npm

This way, we will have a single instance of NW.js across the system, but what if an application requires a specific version of NW.js? Luckily, with npm, we can also install a package locally, and therefore, rely on a particular version that addresses our application. In addition, we can manage local dependencies in the package.json file. With a single command, npm can install/update all the dependencies enlisted there at once.

Let's take a look at how it works on our project. We go to the project root (the file-explorer folder) and run the following command:

npm init -y

It produces a package.json file with the following content:

{ "name": "file-explorer", "version": "1.0.0", "description": "", "main": "main.js", "scripts": { "test": "echo "Error: no test specified" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }

Here, in the name field, we set our application name. Beware that NW.js will use the provided value to name the directory in a system-dependent path for the project persistent data (nw.App.dataPath). So, it shall be a unique, lowercase alpha-numeric, but may include a few special symbols, such as ., _, and -.

Field version expects the application version as a string, conforming to the Semantic Versioning standard (http://semver.org/). What it all boils down to is a composite product version out of three numbers separated with dots. The first number (MAJOR) increments when we make incompatible API changes, the second number (MINOR) increases when we introduce a new functionality, and the last one (PATCH) identifies bug fixes.

In the main field, we let NW.js know where to find our start page HTML. We have to edit the manifest to change its value with index.html:./package.json

{ ... "main": "index.html", ... }

The field scripts accepts a key value object with automation scripts for the project. By default, it has a placeholder for tests. Now, run the following command:

npm run test

The Shell responds with an error message saying no test specified, as we have no test yet. However, we will need a script to start the application. So, we edit package.json again and add to scripts field the following lines:

package.json

{ ... "scripts": { "start": "nw .", "test": "echo "Error: no test specified" && exit 1" }, ... }

Now, we can type npm run start or npm start to run NW.js on the project root, but we do not have the framework installed, yet. We are just about to bring it in.

Manifest fields--such as description/keywords and author--help other people to discover the application as a package. The license field tells people how they are permitted to use the package. You can find more about these fields and other possible options at https://docs.npmjs.com/files/package.json.

Before telling npm to install the framework, we note that the standard version of NW.js doesn't include DevTools, which we definitely will need for development. So, we look for a specific version, the so-called SDK flavor. To find out the package versions that are available for the NW.JS package (nw), we run the following command:

npm view nw dist-tags

Alternatively, we can run the following command:

npm v nw dist-tags

This receives the following output:

{ latest: '0.20.3',

alphasdk: '0.13.0-alpha4sdk',

alpha5sdk: '0.13.0-alpha5sdk',

alpha6sdk: '0.13.0-alpha6sdk',

alpha7sdk: '0.13.0-alpha7sdk',

sdk: '0.20.3-sdk' }

From this payload, we can assume that the latest version at the time of writing is 0.20.3 and that it is accompanied with 0.20.3-sdk. So, we can install the framework, as follows:

npm install [email protected] --save-dev

Alternatively,we can install it, as follows:

npm i [email protected] -D

Actually, since we know that the package has a dist-tag called sdk, we can also do it as follows:

npm i nw@sdk -D

Just after running any of these commands, we can find a new subdirectory named node_modules. There, npm installs local dependencies.

Have you noticed that we applied the --save-dev (-D) option? This way, we requested npm to save the package in our development dependency list. Observe that package.json is changed:

{ "name": "file-explorer", "version": "1.0.0", "description": "", "main": "index.html", "scripts": { "start": "nw .", "test": "echo "Error: no test specified" && exit 1" }, "keywords": [], "author": "", "license": "ISC",

"devDependencies": {

"nw": "^0.20.3-sdk"

}

}

We installed the package as a development dependency because this SDK version is meant only for development. In Chapter 2, Creating a File Explorer with NW.js–Enhancement and Delivery we will examine the distribution and packaging techniques. So, you will see how we can bundle the application with a platform-specific NW.js production build.

Since we have reflected our dependency in the manifest file, we can update this and any further packages any time by running the following command:

npm update

If we lose node_modules(for example after cloning the project from remote GIT repository given the dependency folder is usually in the ignore list), we can install all the dependencies through the following command:

npm i

Have you noticed? In the package.json, we assigned nw package with version in, so called, caret range ^0.20.3-sdk. That means during the install/update process, npm will accept new versions with patch and minor updates, but no major versions.

The following are some useful npm commands:npm i pkg-name: Installs the latest available version of a packagenpm i pkg-name@version: Installs a concrete version of the packagenpm i pkg-name -S: Installs package as a dependency and saves it in package.jsonnpm i pkg-name -D: Installs package as a development dependency and save in package.jsonnpm i: Installs all the dependencies (including development ones) enlisted in package.jsonnpm i --production: Installs dependencies but not development onesnpm list: Shows all the installed dependenciesnpm uninstall nw --save: uninstalls a package and removes it fromnpm un nw -S: shorter syntaxpackage.json

At this point, we have the framework instance and package.json pointing to index.html. So, we can run the only script we have defined in the manifest file so far:

npm start

First, run it on NW.JS in Ubuntu:

Then, run it on NW.JS in windows:

Finally, we run it in macOS:

NW.js created a window and rendered index.html in it. It took the default Window parameters. If we want to customize them, we will need to edit package.json.

First, we will add the window field that accepts an object with the following properties:

window.icon