Prut Udomwattawee
Prut Udomwattawee

Reputation: 691

Basic NodeJS require syntax

I have a question about this basic syntax for NodeJS for require syntax please.

In this repositories,

https://github.com/alduro/generator-flux-webapp/blob/master/app/templates/src/app.js

It uses this code on line 10:

var {Router} = require('director');

Then on line 40:

var router = new Router(routes).configure({html5history: true}).init();

This works.

But If I change from var {Router} = require('director'); to var Router = require('director');.

It will throw Exception, TypeError: Router is not a constructor.

It doesn't work anymore.


So my question is what is {variable} mean?

Thank you for your time.

Upvotes: 3

Views: 1609

Answers (1)

btmills
btmills

Reputation: 4542

The line var {Router} = require('director'); is taking advantage of ES6 object destructuring. An equivalent line would be var Router = require('director').Router;. The director module exports an object which has a property named Router. The destructuring is simply a shorthand way of declaring a variable named Router and initializing it with the value of the object's property by the same name.

Update: changed the object destructuring link to point to a better reference.

To see an example of this in action, try it out using Babel's REPL. (Babel used to be 6to5.)

There are multiple different (and mostly equivalent) ways to accomplish this same thing:

var Router = require('director').Router; // Pure ES5
var {Router: Router} = require('director'); // ES6 named destructuring
var {Router} = require('director'); // ES6 destructuring shorthand
import {Router} from 'director'; // ES6 module import

Upvotes: 8

Related Questions