Himmators
Himmators

Reputation: 15006

Can I pass variable to required file?

In express, I'm trying to move my minification to a requierd file:

app.js:

var app = express();
var minify = require("./minify.js");

In that file I try to set my template engine.

minify.js:

var app = express();
app.engine('html', mustacheExpress());

Later when I try to use to use the rendering engine in app.js, I get the error that no template-engine is set. It works if I run it all in the same file. I think the problem is that I declare the app-variable twice. How can I pass the app-variable into minify.js?

Upvotes: 3

Views: 1227

Answers (2)

Nicolas Leucci
Nicolas Leucci

Reputation: 3349

You can pass 'app' from app.js to your minify by using function in your module like Andrey said. You can do it like this too for example :

minify.js

module.exports = {
    setAppEngine : function(app) {
        app.engine( [...] );
    }
}

And calling it like this in your app.js:

app.js

var app = express();
var minify = require("./minify.js").setAppEngine(app);

This solution is very useful because you can set and call others methods in minify.js. For example, you can do with the same code in minify.js:

app.js

var app = express();
var minify = require("./minify.js");

minify.setAppEngine(app);

Upvotes: 3

Andrey Popov
Andrey Popov

Reputation: 7510

The problem is that you define new app variable, and you currently instantiate brand new express instance by calling express().

What you need to do is start using functions so that you can pass params (there are other methods too, but this is one that will work for you):

// app.js
var app = express();
var minify = require('./minify'); // don't include .js!
minify(app); // CALL the function that minify.js exports, passing params

// minify.js
module.exports = function(app) {
    // because app comes as a parameter, it's the very same you've created in app.js
    app.engine('html', mustacheExpress());
}

Again, there are many different methods and maybe proper approaches, depending on what you want to do, but this will do the job in your case. Read more about NodeJS and it's require system.

Upvotes: 6

Related Questions