Skip to content

Instantly share code, notes, and snippets.

@jc00ke
Last active August 29, 2015 14:14
Show Gist options
  • Save jc00ke/1085352bd8673c579ffa to your computer and use it in GitHub Desktop.
Save jc00ke/1085352bd8673c579ffa to your computer and use it in GitHub Desktop.
Requires in js
// a.js
var add = function(a, b) {
return a + b;
};
module.exports = add;
require('./a');
require('./b');
// Want it to generate something like this:
"use strict";
// b.js
// a.js
var add = function(a, b) {
return a + b;
};
console.log(add(2, 3));
// But it generates:
"use strict";
// b.js
require("./foo");
console.log(add(2, 3));
// a.js
var add = function (a, b) {
return a + b;
};
module.exports = add;
// b.js
require('./a');
console.log(add(2, 3));
@samolsen
Copy link

samolsen commented Feb 4, 2015

In b.js:

var add = require('./a');
console.log(add(2, 3));

@samolsen
Copy link

samolsen commented Feb 4, 2015

And a note about app.js- each module is only loaded a single time, at which point its export is cached in memory. So if you want to reuse b, you will want to export a function or an object.

b:

var add = require('./a');
module.exports = function () { console.log(add(1,2)); };

app:

var b = require('./b');
b();
b();

@jc00ke
Copy link
Author

jc00ke commented Feb 4, 2015

I was wanting to do this for front-end only, via gulp, and happened upon https://www.npmjs.com/package/gulp-resolve-dependencies

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment