Rishav February 2016

Coffeescript: How to import express module in one line

Currently, I have to write

app = require 'express'
app()

To get the equivalent Javascript:

var app;  
app = require('express');
app();

How can I do this in one line?

Answers


MT. February 2016

You could do something like this: require('express')(). But the downside to this approach is that you'd lose access to the app variable.


Lenar Fattahov February 2016

Try this

do app = require 'express'


user1256169 February 2016

There are multiple ways to do what you're asking...

For the correct answer (has the exact javascript output you want), try one of these:

app = require 'express'; do app
app = require 'express'; app()

Some other options would be:

(app = require 'express') null
do app = require 'express'
app = require 'express'; app null

Which result in slightly different Javascript output, but work exactly the same.


Leonid Beschastny February 2016

I want to clear thing up here.

First of all, here is the most common way to import express module and create an application:

express = require 'express'
app = express()

app variable here holds a freshly created express application, while express variable holds the framework itself.

Now, let's say you don't need express framework here, only an application. In this case you could write:

app = do require 'express'

And if you don't need a variable holding your application, you could write something like that:

do express = require 'express'

Though I can't imagine why anyone would want it. Of course, you could chain everything:

do express = require 'express'
  .use(express.static('public'))
  .listen(3000)

But for me it looks like a mess.

Post Status

Asked in February 2016
Viewed 3,322 times
Voted 10
Answered 4 times

Search




Leave an answer