Friday, June 3, 2022
HomeWeb DevelopmentConstructing an app with Subsequent.js and Electron

Constructing an app with Subsequent.js and Electron


For the reason that introduction of Node.js, fundamental net applied sciences (HTML, CSS, and JavaScript) have grown a lot that we are able to now construct multi-device/multi-platform purposes with them. This huge growth additionally resulted within the introduction of frameworks and libraries, which simplified our job even additional. Subsequent.js and Electron are vital examples on this record.

On this article, we’ll be exploring Nextron, a package deal that mixes the highly effective options of Subsequent.js and Electron to allow us to create multi-platform desktop purposes within the best and most gratifying method ever.

We’ll cowl the next sections:

Stipulations

The next stipulations are required to observe together with this tutorial:

  • Familiarity with JavaScript
  • Primary familiarity with the command line/terminal
  • Earlier expertise working with Subsequent.js and Electron may assist, however is just not required

Establishing your Nextron venture

You possibly can simply create a brand new Nextron software by operating:

npx create-nextron-app appName

Nextron additionally gives numerous instance templates that assist TypeScript in addition to standard CSS frameworks, comparable to Tailwind CSS, Ant Design, Materials UI, and Emotion. All the templates will be discovered right here, and after deciding on which to decide on on your venture, you’ll be able to set up them by prefixing the set up command with the popular instance template together with the --example flag. So if you wish to use the TypeScript and Tailwind templates, you’ll need to run:

npx create-nextron-app appName --example with-typescript-tailwindcss

Working the set up command will create all the required information and directories for our venture. Nevertheless, we’ll nonetheless want to put in all of the required dependencies with the command under:

npm set up
# OR
yarn

As soon as that is accomplished, we are able to begin our software with:

npm run dev
# OR
yarn dev

It will instantly open a brand new window for our software, as proven within the screenshot under:

Opening New Window For Our Application

It’s also possible to shut the dev software in order that you’ll be able to entry the applying fullscreen.

The file construction for a Nextron venture

Whereas there could also be minor modifications, principally relying on the instance template you select throughout set up, the file construction for a typical Nextron venture is as follows:

File Structure For Typical Nextron Project

And as you might need observed, all of the Subsequent.js-related code is positioned contained in the /render folder. Another information and directories that you just may not be aware of embrace:

  • most important/helpers — This listing exports a module referred to as createWindow, which makes use of Electron’s BrowserWindow perform to create our desktop software window. We are able to configure the default app window choices right here, comparable to its preliminary measurement and place
  • most important/background.js — This file is the place the createWindow perform is initialized and is accountable for serving our Subsequent.js software as an Electron software
  • sources/ — We might put our desktop software sources, comparable to app icons, right here

How Nextron works

It’s fairly simple to understand how Nextron works behind the scenes. It mechanically checks in case your software is operating in growth mode or in manufacturing. If in growth mode, Nextron takes the localhost URL generated by operating a Subsequent.js software and serves it as an Electron app. Nevertheless, if in manufacturing, Nextron takes the static information generated from a Subsequent.js construct and renders them as a substitute.

Pages

Pages perform precisely the identical method as they might in an ordinary Subsequent.js software, with no exception. To attempt issues out, let’s create a brand new pattern.js file contained in the renderer/pages listing with the next content material:

import Hyperlink from "subsequent/hyperlink";

const pattern = () => {
  return (
    <>
      <div>
        <h1>Hiya world</h1>
        <p>Welcome to pattern web page</p>
        <Hyperlink href="https://weblog.logrocket.com/dwelling">
          <a>Go Residence</a>
        </Hyperlink>
      </div>
    </>
  );
};

export default pattern;

And in addition replace the default dwelling.jsx file on this identical listing with the content material under, in order that it hyperlinks to our new web page as a substitute:

import Hyperlink from "subsequent/hyperlink";

const Residence = () => {
  return (
    <>
      <h1>Hiya World</h1>
      <p>Welcome to my Nextron desktop app</p>
      <Hyperlink href="https://weblog.logrocket.com/pattern">
        <a>Go to pattern web page</a>
      </Hyperlink>
    </>
  );
};

export default Residence;

We now have the next outcomes:

Results For Nextron Desktop Application

Utilizing layouts

Layouts function simply as they might in an everyday Subsequent.js software, with no exceptions both. For instance, suppose we’ve got a navbar that we wish to share throughout a number of pages in our desktop software. First, we’ll must create our structure file; for instance, a brand new structure.js file inside the /renderer listing with the next content material:

const Format = ({ youngsters }) => {
  return (
    <>
      <nav>
        <h2>Nav Brand</h2>
        {/* extra navbar code right here */}
      </nav>
      <most important>{youngsters}</most important>
    </>
  );
};

export default Format;

And since Nextron doesn’t mechanically embrace the _app.js file, which might usually include an software created with the create-next-app package deal, we’ll need to create one manually as nicely and embrace our structure:

//_app.js
import Format from "../structure";

export default perform MyApp({ Part, pageProps }) {
  return (
    <Format>
      <Part {...pageProps} />
    </Format>
  );
}

With slightly CSS utilized to the navbar and the pages we’ve beforehand generated, we’ll get the next outcomes:

CSS Applied To Navbar

Creating new home windows

Whereas the usage of that is very unusual, additionally it is doable to programmatically create new home windows. We’d usually have used Electron’s BrowserWindow to perform this, however Nextron already exports a helper methodology referred to as createWindow for us, which we are able to use as a substitute.

Assume we wish to open the /pattern web page we created earlier in a brand new window. We’ll must first replace most important/background.js to include assist for this new window:

import { app, ipcMain } from "electron";
. . .

  const mainWindow = createWindow("most important", {
    width: 1000,
    peak: 600,
  });
  const sampleWindow = createWindow("pattern", {
    width: 700,
    peak: 400,
    present: false,
  });

  if (isProd) {
    await mainWindow.loadURL("app://./dwelling.html");
    await sampleWindow.loadURL("app://./pattern.html");
  } else {
    const port = course of.argv[2];
    await mainWindow.loadURL(`http://localhost:${port}/dwelling`);
    await sampleWindow.loadURL(`http://localhost:${port}/pattern`);
  }

  ipcMain.on("show-sample", () => {
    sampleWindow.present();
  });
. . .

Within the code offered above, instantly after creating the mainWindow, we create one other window (sampleWindow), setting its preliminary width and peak to 700×400 and likewise setting its present worth to false in order that this window is just not seen by default. And utilizing Electron’s ipcMain occasion emitter, we’re listening for an occasion show-sample, in order that when this occasion is emitted, we show the brand new sampleWindow.

The subsequent step could be to emit this occasion programmatically, and we are able to additionally try this simply with ipc in a web page. For instance, in render/dwelling.jsx:

import electron from "electron";
const ipcRenderer = electron.ipcRenderer || false;

const Residence = () => {
  const openWindow = () => {
    ipcRenderer.ship("show-sample");
  };

  return (
    <>
      <h1>Hiya World</h1>
      <p>Welcome to my Nextron desktop app</p>
      <button onClick={openWindow}>Open pattern web page</button>
    </>
  );
};

export default Residence;

If we run our software, we’ll have the next output:

Nextron Desktop App With New Window

Moreover, we are able to additionally open an exterior URL in a brand new window by including the goal=_blank attribute or utilizing a JavaScript window.open() methodology to open the goal URL.

Electron APIs

Browser-based APIs and the Electron APIs work graciously too, and you may instantly import them into any web page. An instance is the browser notification API, which we are able to make the most of on a web page like under:

const showNotification = () => {
  const notificationTitle = "My Notification 🔔";

  new Notification(notificationTitle, {
    physique: "It is a pattern notification.",
  }).onclick = () => console.log("Notification Clicked");
};

And any time we carry out an motion that triggers the showNotification perform, we’ll instantly get a notification on our desktop. Right here’s an instance of a macOS notification:

MacOS Notification

Constructing a demo app

When you’re carried out coding your software, you’ll undoubtedly wish to generate an executable file so that you could share the applying with others. Nextron handles this with electron-builder. We are able to generate the executable for our Nextron venture with the command under:

npm run construct
# OR
yarn construct

It’s also possible to replace the script part in your package deal.json file to incorporate different construct choices:

. . .
{
  "scripts": {
    "construct": "nextron construct",
    "construct:all": "nextron construct --all",
    "construct:win32": "nextron construct --win --ia32",
    "construct:win64": "nextron construct --win --x64",
    "construct:mac": "nextron construct --mac --x64",
    "construct:linux": "nextron construct --linux"
  }
}

So, if we wish to generate an executable for Home windows 64 bit, we’ll use the next command:

npm run construct:win64
# OR
yarn construct:64

Conclusion

On this article, we’ve checked out Nextron, a JavaScript package deal that enables us to effortlessly create desktop purposes with Electron and Subsequent.js. We checked out creating new pages, software structure, new home windows, utilizing Electron APIs, and lastly producing executable information on your software.

LogRocket: Full visibility into manufacturing Subsequent.js apps

Debugging Subsequent purposes will be troublesome, particularly when customers expertise points which are troublesome to breed. For those who’re concerned about monitoring and monitoring state, mechanically surfacing JavaScript errors, and monitoring sluggish community requests and part load time, attempt LogRocket.

LogRocket is sort of a DVR for net and cell apps, recording actually every part that occurs in your Subsequent app. As an alternative of guessing why issues occur, you’ll be able to mixture and report on what state your software was in when a difficulty occurred. LogRocket additionally displays your app’s efficiency, reporting with metrics like consumer CPU load, consumer reminiscence utilization, and extra.

The LogRocket Redux middleware package deal provides an additional layer of visibility into your consumer periods. LogRocket logs all actions and state out of your Redux shops.

Modernize the way you debug your Subsequent.js apps — .

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments