How to use sugar.js in nodejs?

5.8k Views Asked by At

http://sugarjs.com/

It's a libary so I can load it in browser directly. It's also a npm package, but how can I use it as a moudule?

In browser, load a js file will change the objects easily, but is not the same while working in nodejs, and I can't figure it out.

3

There are 3 best solutions below

0
Andrew On BEST ANSWER

Sugar isn't used as a standard CommonJS module, as the entire point of the library is to modify built-in prototypes. One you require it into your project, all the built-in objects will be extended and you can use them from there.

Edit: This is now no longer true as of v2.0.0. Prototype modification is now opt-in so you can use Sugar just like any other node module using the exported object. For more, see https://sugarjs.com/quickstart/

3
Justin Beckwith On

You just install the module:

npm install sugar

then use it just like the API says:

var http = require('http');
var sugar = require('sugar');

http.createServer(function (req, res) {

    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('hey_there_good-lookin'.camelize());

}).listen(process.env.PORT || 8080);
8
B T On

Don't use sugar.js - it modifies native prototypes so EVERYTHING will use them - not just your module. Doing this is incredibly insidious, its not modular, and it will bite you in the ass when you least expect it.

Its worth saying it again: don't use any module that modifies native prototypes outside the (very reasonable) context of polyfilling. Don't use Sugar.js. Espcially in node.js - there's a module system there for a reason. I have personally run into awful issues with things that modify native prototypes. Weird things can happen deep in the bowels of your code.

Here's some more information on why modifying native objects is bad:

http://www.nczonline.net/blog/2010/03/02/maintainable-javascript-dont-modify-objects-you-down-own/

UPDATE: It sounds like Sugar v2.0.0 now treats extending natives as opt-in, which is much better (since natives aren't extended by default).