avasin
avasin

Reputation: 9726

Front-end dependencies via npm: how does it work?

I've installed backbone via npm, it is placed in node_modules folder (not in web root) how can i include it in my index.html file?

Upvotes: 3

Views: 1521

Answers (3)

Ali
Ali

Reputation: 10453

Front-end dependency I would recommend using Bower. There are many components available for you to use and they are really easy to setup.

Upvotes: -1

Myrne Stol
Myrne Stol

Reputation: 11438

It's possible to write front-end code entirely based on CommonJS (i.e. Node-style) modules.

If you install front-end dependencies through npm you can use a package bundling tool like Browserify to bundle all dependencies into one file. This way you can use the browser-dependent packages in the same way you use server-side packages: with Node's require function. You just require a module (either in node_modules dir or a regular file) and work with it.

Base use of browserify is really simple: Just do browserify clientcode.js > webroot/clientbundle.js, where webroot is your web root. Then include clientbundle.js in your html file.

clientcode.js should be the client's "main" script, comparable to the "app.js" (or similar) of an Express app or so. It can be as big as you want, but you could just as well use it only as bootstrap code to run functions defined in other CommonJS modules.

Note that you can easily mix browserified dependencies with regular dependencies. Any scripts that you include beforehand (say a non-browserified jquery) will just become a global, and browserify does not prevent you from accessing globals.

Beware though: Some packages distributed via npm based on client-side libraries do not conform (entirely) to CommonJS spec. Some may not export anything, some may (unexpectedly) create globals, etc.

See also Backbone app with CommonJS and Browserify .

Some alternatives to browserify:

I haven't tried them though.

Upvotes: 7

Matthew Sullivan
Matthew Sullivan

Reputation: 78

While the idea of using npm for both backend and frontend may sound tempting–it certainly did to me–try Bower or Ender.js instead for frontend dependencies. I personally prefer bower, because I can more easily include it into my requireJS module structure. It will keep you from foaming at the mouth with frustration.

Upvotes: 2

Related Questions