-1

I'm working on a nuxt project foe which I will need to use the express framework on server side. After creating the nuxt project and selecting the express option during setup I see that there is a new file, server/index.js which provides a starter templare which contains:

const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
const host = process.env.HOST || '127.0.0.1'
const port = process.env.PORT || 3000

app.set('port', port)

// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')

async function start() {
  // Init Nuxt.js
  const nuxt = new Nuxt(config)

  // Build only in dev mode
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  }

  // Give nuxt middleware to express
  app.use(nuxt.render)

  // Listen the server
  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}
start()

I can understand most of this but not:

const { Nuxt, Builder } = require('nuxt')

What does this do?

user1592380
  • 34,265
  • 92
  • 284
  • 515
  • This is a duplicate of [Curly brackets (braces) in node require statement](https://stackoverflow.com/questions/38660022/curly-brackets-braces-in-node-require-statement) – Sam Battat Jan 07 '19 at 17:26

1 Answers1

4

That's the new(ish) object destructuring syntax from the latest versions of the ECMAScript standard.

You can read it as asking for the properties Nuxt and Builder from an object returned from the require('nuxt') statement. Under the hood, you might see something like this in the main file of the nuxt module:

module.exports = { Nuxt, Builder, Somethingelse, MoreObjects, AnotherFunction};

That in itself is a new(ish) shorthand as well, in that it takes a local variable and maps it to a property on an object. Consider:

var number = 5;
var obj = { number : number }; // this is the same as just saying var obj = { number };

Then when you do the const { Nuxt, Builder } = require('nuxt'), you get two constant variables Nuxt and Builder that you can refer to elsewhere in your code.

Paul
  • 35,689
  • 11
  • 93
  • 122