Timothy Deng Timothy Deng - 1 year ago 88
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

which is in

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
can be essentially interchanged because you don't modify these modules. What I'm failing to understand is if
is in
, then why can #1 directly require it (rather than something like
)?. I am further confused because #4 seems to imply app is actually in
. 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 Source
  • #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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download