Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write javascript code that works with client side javascript and server side NodeJs modules

Browserify and lo-dash, do something special. Ok, but should like to be free from other vendor libraries or nodejs modules. I want to write reusable code. So, ...

I can write some javascript code. Also, I can write NodeJs code. Ok: I can write a module for NodeJs, for server-side code but at some point I need to write a NodeJs code to export, for example, a module.

var MyModule = function () {
    this.attribute = 666
}
module.exports = MyModule

But, ... it's a NodeJs module. If I try to include it in client page ...

<script src="lib/myModule.js">

I'll get 'Uncaught ReferenceError: module is not defined'. Why? Maybe, because it's NodeJs code, and not Javascript. Ok but, ... Which are best practice to share same code in client and server side with NodeJs. Ok, I can share a javascript file, and use it in both sides. How can I write a module, that works with a javascript code, that I want to use also in client side?

What I am looking for, is:

Write some javascript code. my_public_file.js:

console.log('I am a javascript snippet')

Then, I want to write a module that works with same code. my_module.js

var lib_public_code = require('some/public/path/my_public_file.js')
var MyModule = function () {
    this.attribute = 666
}
module.exports = MyModule

And, also, I wanto to write a public web page (index.html) that works with the same code

<script src="javascript/my_public_file.js">

Best practices? I am insane?

like image 850
sensorario Avatar asked Dec 26 '22 06:12

sensorario


2 Answers

To make it work both client-side and server-side, just export it if module.exports exists:

var MyModule = function () {
    this.attribute = 666;
};

if (typeof module !== "undefined" && module.exports) {
    module.exports = MyModule;
}

This, and similar ways are used by a lot of libraries to enable packages to be used on CommonJS and the browser (e.g.: jQuery)

like image 98
lante Avatar answered Dec 28 '22 09:12

lante


You install browserify

$ npm install -g browserify

you take your my_public_file.js whatever node code etc.

var lib_public_code = require('some_file.js')
var MyModule = function () {
   this.attribute = 666
}
module.exports = MyModule

you run the magic

$ browserify my_public_file.js -o bundled_public.js

then it works in the browser and the required files are all there.

<script src="bundled_public.js">
like image 26
Dylan Avatar answered Dec 28 '22 09:12

Dylan