Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use node.js module system on the clientside

I would like to use the CommonJS module system in a clientside javascript application. I chose nodejs as implementation but can't find any tutorial or docs on how to use nodejs clientside, ie without using node application.js

I included node.js like this in my html page:

<script type="text/javascript" src="node.js"></script> 

Note that I didn't make nodejs on my local machine, I'm on Windows anyway (I'm aware of the Cygwin option). When I want to use the require function in my own javascript it says it's undefined.

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

My question is, is it possible to use nodejs like this?

like image 383
Nicolas Mommaerts Avatar asked Feb 09 '11 12:02

Nicolas Mommaerts


People also ask

Can I use node modules in browser?

Thanks to some creative engineers, it is now feasible to use Node. js modules in browsers, but not directly. Being able to call Node. js modules from JavaScript running in the browser has many advantages because it allows you to use Node.

Can you use node JS on the frontend?

Node. js is sometimes misunderstood by developers as a backend framework that is exclusively used to construct servers. This is not the case; Node. js can be used on the frontend as well as the backend.


1 Answers

SubStack on github has a module called node-browserify.

It will compress and bundle your modules and deliver it as a single js file, but you use it just like Node.js (example from module readme):

<html>     <head>     <script type="text/javascript" src="/browserify.js"></script>     <script type="text/javascript">         var foo = require('./foo');          window.onload = function () {             document.getElementById('result').innerHTML = foo(100);         };     </script> </head> <body>     foo = <span style='font-family: monospace' id="result"></span> </body> </html> 

From the module description:

Browserify

Browser-side require() for your node modules and npm packages**

Browserify bundles everything ahead-of-time at the mount point you specify. None of this ajaxy module loading business.

More features:

  • recursively bundle dependencies of npm modules
  • uses es5-shim for browsers that suck
  • filters for {min,ugl}ification
  • coffee script works too!
like image 114
Marcello Bastea-Forte Avatar answered Sep 21 '22 03:09

Marcello Bastea-Forte