0

I have two files: a.js and b.js.

a.js:

console.log(require("./b.js")());
module.exports = function () {
   console.log("Hello Mars!");
};

b.js:

module.exports = function () {
    console.log("Hello World");
};

By bundling these files I obtain c.js:

browserify a.js -o c.js

I expect c.js to export a function (that prints Hello Mars when called). By requireing c.js in a node process I get an empty object.

$ node
> c = require("./c.js")
Hello World
undefined
{}
> c()
TypeError: c is not a function
    at repl:1:1
    at REPLServer.defaultEval (repl.js:252:27)
    at bound (domain.js:287:14)
    at REPLServer.runBound [as eval] (domain.js:300:12)
    at REPLServer.<anonymous> (repl.js:417:12)
    at emitOne (events.js:82:20)
    at REPLServer.emit (events.js:169:7)
    at REPLServer.Interface._onLine (readline.js:210:10)
    at REPLServer.Interface._line (readline.js:549:8)
    at REPLServer.Interface._ttyWrite (readline.js:826:14)

Since node has already a module object, how can I tell Browserify to use this module object for the main file, so I will get the Hello Mars function in the module.exports when using require in Node?

I checked out the docs, but I didn't find any option... Maybe I miss something.

I just want to bundle a module (that has dependencies) and require it in a node process.

1 Answer 1

1

You are looking for the following option:

--standalone -s
Generate a UMD bundle for the supplied export name. This bundle works with other module systems and sets the name given as a window global if no module system is found.

You might also want to pass the --node option, to turn off the transformation of Node specific features.

Sign up to request clarification or add additional context in comments.

3 Comments

--node does something else, --require is expected to do this, but it doesn't work. And I also don't really want to create globals. Anyways, -s is the best one yet. Waiting for @substack feedback. :)
What makes you think globals would be created? He option says "This bundle works with other module systems and sets the name given as a window global if no module system is found." Since Node does have a module system, it wouldn't create a global. As for --node: it includes --bare, which says: "This is handy if you want to run bundles in node". It seems that's exactly what you want to do. --require doesn't have anything to do with node.
Right, in fact creating globals when there is no module system is not that bad, but still I search for an option that doesn't do that at all. I want to have export functionality in the bundle file but to not create any globals even when there is no module system. Anyways, accepting for now. :) Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.