Timothy Deng Timothy Deng - 3 months ago 14
Javascript Question

What's the proper way to require in Node.js?

I'm just getting started with Node.js and Electron, and I've seen various ways both in the documentation and in example code on how to require modules. Specifically, I am trying to follow this tutorial. In this particular example, I think I am requiring

app
which is in
electron
.

1) In the tutorial, it has you do:

var app = require('app')


2) In the electron-quick-start example, which is provided by Electron to help you get started, they have you do:

const electron = require('electron')
const app = electron.app


3) In Electron documentation, they use:

const {app} = require('electron')


4) In an Electron boilerplate program, I found:

import { remote } from 'electron'
var app = remote.app


What is going on here? I have mostly seen #1 around the Internet, and it seems that
var
and
const
can be essentially interchanged because you don't modify these modules. What I'm failing to understand is if
app
is in
electron
, then why can #1 directly require it (rather than something like
require('electron.app')
)?. I am further confused because #4 seems to imply app is actually in
electron.remote
. Secondly, is #3 preferred because it's used in the documentation? Or is #4 preferred? The comment in the program for #4 says "Use new ES6 modules syntax for everything". Does this mean this is the future of JavaScript? And of course, I would like to know if these are just syntactic differences or if they actually affect how the program is run.

Answer
  • #1 no longer works in Electron v1.0+.
  • #2 and #3 are equivalent, #3 just uses a destructuring assignment.
  • #4 uses ES6 module import syntax which NodeJS doesn't handle natively yet, so it only works if you transpile your code with Babel, or TypeScript, or some other transpiler that can transform those import statements to require statements.